Code for GLTFLoader

Hi all, I am having troubles still with the GLTFLoader. Basically, I’m loading a GLB that is divided into separate, clickable parts. Below is the code for how I was doing that with OBJ Loader.

Old Code, where objects is initially an empty array :

    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath('models/');
    mtlLoader.load( 'body_model.mtl', function( materials ) {
        materials.preload();
        var loader = new THREE.OBJLoader();
        loader.setMaterials( materials );
        loader.setPath('models/');
        loader.load( 'body_model.obj', function ( object ) { 
            object.children.forEach(child => {
                objects.push(child);
                changeObjectColor(child, whiteColor);
            });
            selectModel=object;
            scene.add(object);
        });
    });

I was able to load the GLTF model into the app which is a start, but I’m still struggling to apply the same features to the newer model.

New Code:

        var bloader = new THREE.GLTFLoader();
    bloader.load('models/body_model.glb', function (gltf){
        scene.add(gltf.scene)
    });

I’ve looked thru the GLTF loader documentation to figure out how to do this, but I’m struggling to translate the old code, into the new code. Thanks for all the help in advance.

Try it like so:

selectModel = gltf.scene;
scene.add( selectModel )

selectModel.traverse( function( child ) {

    if ( child.isMesh ) {

        objects.push( child );
        changeObjectColor( child, whiteColor );

    }

} );

Thanks for the response. Got a type error. Below is the code I ran

        var bloader = new THREE.GLTFLoader();
    bloader.load('models/body_model.glb', function (gltf){
        selecteModel = gltf.scene;
        scene.add(selectModel)
        selectModel.traverse(function(child){
            if (child.isMesh) {
                objects.push(child);
                changeObjectColor(child, whiteColor);
            }
        });
    });

Error:

GLTFLoader.js:58 TypeError: Cannot read property 'traverse' of undefined

or

It looks like you have a typo.

1 Like

worked like a charm. Very grateful guys!