Search code examples
javascriptthree.jsblendergltf

Three.js GLTF change object material to another objects material


So I have this scene which comes from a glb-file that I imported using GLTFLoader. It contains these objects of guys in different colors. Each object has its material (RedMat, BlueMat, GreenMat etc). The materials are made in Blender and they all use the same texture file (this one) which is basically just a color palette. So the different colors of the objects just comes from each material having different UVs.

enter image description here

This works good so far and the objects have the correct colors when I load them using GLTFLoader and display it in my three.js scene (the screenshot is from a three.js render). But I want to be able to update the material of one object, so that for instance the red object takes the material of the green object.

new GLTFLoader().load('myfile.glb', function (gltf) {
    const redGuy = gltf.scene.children.find(x => x.name === 'RedGuy');
    const greenGuy = gltf.scene.children.find(x => x.name === 'GreenGuy');

    redGuy.material = greenGuy.material; // I expect here that the red guy would become green, but nothing happens
    // But if I instead do this:
    redGuy.material = new THREE.MeshPhongMaterial({color: '#FF0000'});
    // that works, but I want to be able to use the materials I already setup in Blender that are in the glb-file
});

Also if I console.log redGuy.material and greenGuy.material in the console they look pretty much identical, which I find weird, they just have different names and ids.

Obviously this is a short snippet to demonstrate my problem, I hope this is sufficient. Otherwise I could upload the whole project and the Blender-file somewhere if that is needed.


Solution

  • Okay so I finally found out the answer. Instead of

    redGuy.material = greenGuy.material;
    

    I should write

    redGuy.geometry = greenGuy.geometry;
    

    In this case the colors of the different objects are determined by the UV coordinates. I thought these would be a part of the material node, but instead it seems they are in the geometry node.