I'm reusing a mesh several times, so I cloned it. I applied new materials to each clone. Unfortunately, when I change the material of one Mesh, it affects all meshes.
Here is my code simplified:
switch (filetype) {
case "fbx":
mesh = LoadFBX(path).clone();
break;
case "glb":
mesh = LoadGLTF(path).clone();
break;
case "gltf":
mesh = LoadGLTF(path).clone();
break;
case "obj":
mesh = LoadOBJ(path).clone();
break;
}
mesh.traverse((mesh, i) => {
if (mesh.isMesh) {
if (mesh.material.length) {
for (let i = 0; i < mesh.material.length; i++) {
mesh.material[i] = mesh.material[i].clone();
if (selected) {
mesh.material[i] = new MeshStandardMaterial({
color: 0x000f40,
});
} else {
let matTemp = new MeshStandardMaterial({
color: 0x000000,
});
mesh.material[i] = matTemp;
}
}
} else {
mesh.material = mesh.material.clone();
if (selected) {
mesh.material = new MeshStandardMaterial({
color: 0x000f40,
});
} else {
let matTemp = new MeshStandardMaterial({
color: 0x000000,
});
mesh.material = matTemp;
}
}
}
});
I tried cloning the materials as well, by using these phrases:
mesh.material[i] = mesh.material[i].clone();
and
mesh.material = mesh.material.clone();
But that didnt change anything.
I also tried cloning the new materials:
mesh.material[i] = matTemp.clone();
and
mesh.material = matTemp.clone();
Still not the right way. Can you help me?