0

So I am having this method of my Car class and I wanted to return the mesh, but it returns as undefined. The problem is that even if I try to show it on console after I get out of carLoader is unndefined too, if I invoke console.log in carLoader.load(..) it's ok . The question is how can I store it so I can use it?

this.loadCarToScene = function ( carsVector,carName ) {


    var carLoader = new THREE.BinaryLoader();

    var mesh;
    carLoader.load( carsVector[Object.keys(carsVector)[0]].url, function( geometry ) { 

        geometry.sortFacesByMaterialIndex();
        console.log("url--->"+carsVector[Object.keys(carsVector)[0]].url);

        var m = [],
        s = carsVector[ Object.keys(carsVector)[0] ].scale * 1,
        p = carsVector[ Object.keys(carsVector)[0] ].position,
        r =carsVector[ Object.keys(carsVector)[0] ].init_rotation;


        for ( var i in carsVector[ Object.keys(carsVector)[0] ].mmap ) {
            m[ i ] = carsVector[ Object.keys(carsVector)[0] ].mmap[ i ];
        }
        mesh = new THREE.Mesh( geometry, m );

        mesh.rotation.x = r[ 0 ];
        mesh.rotation.y = r[ 1 ];
        mesh.rotation.z = r[ 2 ];
        mesh.scale.x = mesh.scale.y = mesh.scale.z = s;

        mesh.position.set( p[0], p[1], p[2]);

        scene.add(mesh);
        return mesh;        

    });

    console.log("mesh---->" + mesh );

}
Ioana B
  • 195
  • 3
  • 16
  • the load function is asynchronous so the `console.log("mesh---->" + mesh );` runs before the model is loaded. Also, the `mesh` variable is created inside the `loadCarToScene` function, you probably want to declare this variable outside of the function for easy access. Also `return mesh` is returning to nowhere. – 2pha May 31 '18 at 23:39
  • I want to declare the mesh variable outside and access the mesh but if the load function is asynchronous I guess there is no way of doing it. I am struggling for almost 12 hours. I wanted to make the Car class to load the mesh and after to get the mesh and add it into a variable and then to the scene. :( – Ioana B Jun 01 '18 at 01:16
  • Many different ways to achieve what you want, a callback function send to `this.loadCarToScene` that gets called from the `carLoader.load` callback may be the easiest without changing too much of what you already have. – 2pha Jun 01 '18 at 02:43
  • Maybe https://stackoverflow.com/questions/50276831/threejs-store-jsonmodel-into-a-class-variable/50281662#50281662 helps a bit :) – Mugen87 Jun 01 '18 at 07:35
  • Thank you for your help, I used callback function and finally works as I wanted. I did something similar like here https://stackoverflow.com/questions/25945301/three-js-load-multiple-objects-asynchronous-issue – Ioana B Jun 01 '18 at 13:21

0 Answers0