Three.js options

Hello.

faced this question

const geometry = new THREE.BoxGeometry( 5,5,5 );
const material = new  THREE.MeshBasicMaterial({color:'black'});
const mesh = new THREE.Mesh(geometry,material);
scene.add(mesh);

const mesh2 = mesh.clone();
mesh2.position.x = -8;
mesh2.material.color.set(0xdddddd);
scene.add(mesh2);

I need to change the color of the 2nd object, but this option changes the color of both objects.

How can I do that?

Cloning a mesh does not clone its material - it just reuses the original one by reference. You can copy the material manually though:

const mesh = new Three.Mesh(geometry, material);

const mesh2 = mesh.clone(); // NOTE This is a "shallow clone", it uses the same geometry and material as the previous mesh
mesh2.material = mesh.material.clone();
mesh2.material.color.set(0xdddddd);

(This applies to cloning other things in Three as well - so as an example, if you’d clone a material, it’d reuse textures of the original one unless you clone them manually.)

2 Likes

Thanks for the explanation