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) :
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?
