Loader THREE.js OBJ Objects

I have a problem accessing an object outside the bounds of events. If I put an object in an array and checked this array, it is also empty, but in scope it is full. I need to know how I can access an 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. 
+6
source share
1 answer

This is not about scope; It is empty because you need to wait for the bootloader to load before you see the trees there - this is what addEventListener ("load") does. The last line of your code snippet is executed before your download.

Your code snippet is confusing; it does not immediately show what you are trying to do with the for loop. You create many boot loaders and attach a load event listener to them. But your call to loader.load () after the loop, so it will apply to the last bootloader. You probably want to move the creation of the loader object outside the for loop or the call to loader.load inside the loop.

+2
source

All Articles