Default material recall for GLTF/GLB

Hey everyone!
I have a scene that highlights a section of a gltf file when the user selects a part and I’m looking to revert the material back to the GLTF default material when selecting another part? (Selecting the building will highlight with blue, then selecting a car will deselect the building and only highlight the car) What is the correct method to store the default material of the gltf so it can be restored?

Here is the JSFiddle I’m working on

I have read about the way information can be stored with Material.userData
I’ve only seen examples that call out Hex colors but nothing that calls for the default material.

Should it be MeshPhysicalMaterial in the loader of the model?

material.userData.defaultMaterial = new MeshPhysicalMaterial( );

then use material.userData.defaultMaterial in an if…else statement?

   function onClick(event) {
      event.preventDefault();
      mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
      mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObject(scene, true);
      if (intersects.length > 0) {
         part = intersects[0].object;
         part.material = part.material.clone();
         part.material.color.set( 0x34CDEF );
         part.material.emissive.set( 0x092F87 );
      } else {
        if (part !== null) {
        part.material.copy( part.material.userData.defaultMaterial );
        part = null;
      } } }

…or is there a better way?

Setting .userData seems fine, yes. You could also keep a map from the object to its original material, such as:

const originalMaterials = {};

// ...

if (!originalMaterials[part.uuid])  {
  originalMaterials[part.uuid] = part.material;
}

// ...

In your code snippet above, a new material will be created each time you highlight the same part. It might be better to reuse the highlight material as well.

1 Like

@donmccurdy thank you for your expertise! I will try that and see if I can make it work :slight_smile: