Adding instances of Mesh to array isn't working

Viewed 30

I'm trying to create several duplicates of a mesh randomly distributed around my THREE.Js scene. I've used the clone() method in a for loop to do so. The array shows a list of the clones I created in the console, but when I try to call the individual elements of the array, I get undefined returned to me in the console. This is the code I tried:

let ball = new THREE.Mesh();
loader.load( './ball.gltf', function ( gltf ) {
    gltf.scene.traverse(function(model) { //for gltf shadows!
        if (model.isMesh) {
          model.castShadow = true;
          model.material = sphereMaterial;
        }
    });
    ball = gltf.scene
    
    scene.add( ball );

    for (let i = 1; i <= 9; i++) {
        let newBall = ball.clone()
        scene.add(newBall)
        newBall.position.set(Math.floor(Math.random() * 20) * 2 - 10, Math.floor(Math.random() * 20) * 3 - 10, Math.floor(Math.random() * 20) * 2 - 10)
        pos_arr.push(newBall)
    }
    
}, undefined, function ( error ) {
    console.error( error );
} );

This is what I get when I call console.log(pos_arr) :

enter image description here

Then, if I were to call, say console.log(pos_arr[2]), I would get undefined.

By any chance, does anyone know what's going wrong here?

1 Answers

The usual root cause of this issue is that you access pos_arr too early. Meaning before the onLoad() callback of GLTFLoader has been executed.

There are various ways to fix this issue and the solution mainly depends on how you have structured your app. One approach that can always be used is to pass an instance of LoadingManager to all of your loaders and use its onLoad() callback to finish your scene setup or start object access.

Related