Search code examples
javascriptthree.jscameraloaderfbx

Threejs fbx loader add objects to scene but i they aren't on the children array


Following the threejs.org FBX loader example, i got my model to be loaded with this function:

this.obj = null;

var loader = new THREE.FBXLoader();
var objs = []

function load_init( object ) {
    mixer = new THREE.AnimationMixer( object );

    console.log("pushing to objs...");
    objs.push(object);
    console.log(objs[0]);

    object.traverse( function ( child ) {
        if ( child.isMesh ) {
        //console.log(child)

        //console.log(child.material.length)

        const oldMat = child.material;
        var newMat = new THREE.MeshBasicMaterial();

        // if(oldMat.length == undefined)
        // {
        //     console.log(newMat.copy(oldMat));

        //     child.material = newMat;

        //     child.material = new THREE.MeshBasicMaterial( {  
        //     color: oldMat.color,
        //     } );
        // }
        // else
        // {
        //     for(var i = 0; i < oldMat.length; i++)
        //     {
        //         child.material[i] = new THREE.MeshBasicMaterial( {  
        //         color: oldMat[i].color,
        //         } );
        //     }
            // }
        }
    } );

    object.position.z -= 200;
    object.position.y -= 250;
    var action = mixer.clipAction( object.animations[ 0 ] );
    action.play();
    scene.add( object );
} 

var true_load = load_init.bind(this);
console.log("printing objects...");
loader.load( 'Anims/Capoeira.fbx', true_load);

console.log(objs);//seems to have things there
console.log(objs[0]);//prints undefined

This adds the object succesfully and i can see the animation playing. The problem is: I need to access the object loaded to the scene and mess around with it's variables(mostly material shading and color). When i do console.log(scene.children) i can see it printing all the children. There are 4 total (A light, a ground, a grid helper and the loaded object). However, when i print the length, it'll only say there's 3 objects and if i try to access the loaded object directly through the children array or by getting the object by ID or name, i'll get undefined. I've also tried to change the function to return the loaded object and even set a variable called loaded_object, but i'll leave the function unfedined aswell.


Solution

  • Consider using THREE.LoadingManager. These issues are most likely due to the asynchronous nature of the loader.load method.

    In the THREE.LoadingManager.onLoad method, you should be able to access everything correctly.