Travers trough all layers in a glb file and add different materials - not working

Hi. I try to travers trough all layers in a loaded glb file and give each layer a different material, but it’s not working. Any ideas where I do wrong?

function doorMaterial (setLayer) {

const assetPath = '../models/greenhouse/';       // model-folder
const loader = new THREE.GLTFLoader();
loader.load('g-door.glb', function(object){  

    var i = 0;

    object.scene.traverse(function(child){     // travers trough all the layers in the glb file

        if (i == 0) {
            doorMaterial1 = new THREE.MeshPhongMaterial ({color: 0x3333ff, opacity: 0.5, transparent: true, }); // denne funker
            child.material = doorMaterial1;

        if (i == 1) {
            doorMaterial2 = new THREE.MeshPhongMaterial ({color: 0x339933, opacity: 0.5, transparent: true, });  
            child.material = doorMaterial2;

        if (i == 2) {

            doorMaterial3 = new THREE.MeshPhongMaterial ({color: 0x330033, opacity: 0.5, transparent: true, }); 
            child.material = doorMaterial3; 
        i ++;

    model = new THREE.Object3D();
    model.add(object.scene.children[0]); // skjønner ikke hvorfor man add'er [0], men scenen [1] ?



Please be more specific. What exactly does not working? Can you please describe in more detail the expected and actual result? So far it’s not clear to me what you are trying to do with your shared code.


I want to load one glb file, it contains three object; 1 - window-glass, 2 - wood-frame, 3 - doorknob. Then I want to travers through all three loaded objects, sort them out one by one, and give each object a unique material.

But when I run the code the Door do not have this materials added.

In this case, it’s not necessary to work with layers. In general, you might have more success if you select objects contained in your asset hierarchy via name by using Object3D.getObjectByName(). That works better since there might be intermediate nodes in the hierarchy that you select accidentally with your current approach.

Thanks Mugen87, I will try with Object3D.getObjectByName()