Beginner Question: Using a For Loop to add multiple cubes that all animate

Hey there,
I’ve managed to draw some cubes with a for loop. However my animation is only animating one of the cubes, not all.

This is a link to the codepen:
And here is the code in my init() function:

  var geometry = new THREE.BoxGeometry();
  var material = new THREE.MeshLambertMaterial({
    color: 0x00ff00,
    wireframe: true,

  for (let i = 0; i < 3; i++) {
    cube = new THREE.Mesh(geometry, material);
    cube.position.x = i;

and here is the code in my render function:

function render() {
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);

I’m sure it’s quite a simple solution that I’m overlooking. Any help would be appreciated, thanks!

You keep overwriting your cube in the loop. Use an array and you can address each cube via the index.

 var cube = [];

for (let i = 0; i < 3; i++) {
    cube[i] = new THREE.Mesh(geometry, material);
    cube[i].position.x = i;
function render() {
  cube[0].rotation.x += 0.01;
  cube[0].rotation.y += 0.01;
// use other indexes....
  renderer.render(scene, camera);


Check this out too:

1 Like

That did it, thanks!