Search code examples
javascriptthree.jstextures

Three.js Assigning map to object.children[0] changes whole object's map


i am trying to assign map to every object loaded with OBJLoader in one obj file, which is working. The problem is when i am trying to assign other map to only one object from that file and keep the rest with previous map. It changes map for every object.

function loadOBJ( geometry, name ) {
loader.load( geometry, function( object ){
    object.traverse( function (child) {
        if ( child instanceof THREE.Mesh ) {
            child.material.map = map;
            child.material.envMap = textureCube;
            child.castShadow = true;
            child.receiveShadow = true;
            child.material.needsUpdate = true;
        }
    });

    object.children[0].material.map = new THREE.TextureLoader().load("img/ground.jpg");
    object.name = name;
    scene.add( object );
    console.log(object.name);
}); }

Even when i run traverse only for object.children[0] and assign the map there, the result is same. What am i doing wrong?


Solution

  • If you change a property of a material, that change will appear on all renderable objects that share that material. That is likely what is happening in your case.

    Use this pattern:

    newMaterial = object.children[ 0 ].material.clone();
    
    newMaterial.map = new THREE.TextureLoader().load( "img/ground.jpg" );
    
    object.children[ 0 ].material = newMaterial;
    

    three.js r.75