I have a problem regarding accessing the object outside the event boundries. If I put the object in an array and checkout that array the array is also empty but in the event scope it is full. I need to know that how could I access the object outside the event scope.
for (var i = 0; i < 19; i++){
var loader = new THREE.OBJMTLLoader();
loader.addEventListener( 'load', function ( event ) {
var tree = event.content;
myWorld.setWorldTreePosition(multiplier);
tree.position.y = 0;
tree.position.x = myWorld.myTreePosition.position.x;
tree.position.z = myWorld.myTreePosition.position.z;
tree.rotation.x = -(Math.PI / 2);
tree.scale.set(10,5,5);
scene.add( tree );
collidableMeshList2.push(tree);
tree.castShadow = true;
//collidableMeshList.push(tree);
multiplier += 500;
console.log(collidableMeshList2); // here it is full of trees.
}
);
loader.load( 'obj/Palm_Tree.obj', 'obj/Palm_Tree.mtl' );
//outside this all becomes empty.
console.log(collidableMeshList2); // here is list is empty but I don't know why.
It's not about the scope; It's empty because you need to wait for the loader to load the object before you'll see the trees in there - which is what the addEventListener("load") does. The last line of your code snippet executes before your load function.
Your code snippet is confusing, it's not immediately apparent what you are trying to do with the for loop. You are creating many loaders and attaching load event listener to them. But your loader.load() call is after the loop, so it will apply to the last loader. You'll probably want to move your loader object creation up outside the for loop, or the loader.load call inside the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With