Change imported mesh material or remove mesh

Repo with example:

Question:
I want to highlight one of the boxes on hover. I dont understand, why all boxes are highlighted. In line 182 I log the selected name of the respective mesh, thats fine but in line 188 I change the color of the hovered mesh and all meshed are recolored.

Why is it not possible to modify an individual mesh from a gltf model with scene.getObjectByName()? scene.getObjectByName(name).remove() for example, dont work either.

PS: I googled for hours and read a lot in the docs… but I find no similar example. The most “interactive” demos (Raycaster) use three generated meshes and not imported ones.

The problem is that all you box meshes share the same material. By changing the color of single box, you share the color for all of them.

The solution is to clone the material for each mesh in your onLoad() callback like so:

gltf.scene.traverse( function ( child ) {

	if ( child.isMesh ) {

		child.material = child.material.clone();

	}

} );
2 Likes

Thats it, thanks! :slight_smile:

To .remove() a mesh from a imported “scene” I have to clone it to seperate instances too?

No. Assuming your mesh has no child objects, removing it does not affect other ones in your scene.


(Screenshot: My imported glTF, viewed in glTF Viewer)

I’ve imported a scene with multiple meshes. But how can I remove Cube18 for example? scene.getObjectByName(“Cube18”).remove() does not work.

You are not using the method correctly. Object3D.remove() has a parameter. It should be:

var object = scene.getObjectByName(“Cube18”);
scene.remove( object );

Not working :frowning: . I’ve updated the repo.
I get the right objects name (console), but it is still there. I want to remove it on hover, only for testing…

Oh, the problem is that your cubes are no direct children of scene. So you need this code:

var parent = object.parent;
parent.remove( object );

BTW: You call controls.update(); twice. One time in animate() and one time in update(). A single call per frame is sufficient.

4 Likes

It works now! Thank you so much! :blush:

@Mugen87 Is there any way to hide the mesh instead of removing it. I am hide it by assigning a transparent material to the mesh but that way it is still there in the scene and takes clicks. I want to hide the mesh such that it doesn’t take clicks.