Change gLTF Material OnClick

Wondering if there is an easy way to switch materials back and forth on click with imported GLFT’s. At the moment it’s pretty easy to set something to a new material i.e intersects[0].object.material.color.set(0xFF0000);

But it doesn’t seem to be the solution needed for resetting the gltf back to the original material when i click off of the geometry.

I’m loading geometry and setting a material like this, but is it possible somehow to have multiple global material variables where my var Material becomes var OriginalMaterial and I can define a number of highlighting materials which i am able to switch on click. I’m using a switch statement to apply specific functions to specific geometries i.e some when clicked will be green and others will be red but when i exit they should all be silver.

Any suggestions or advice would be greatly appreciated as it seems to be easy to retain the materials or colors i.e get/set with three.geometry but i need to do it with imported geometry!

Thanks, GLTF loading example below!

          var loader = new THREE.GLTFLoader(loadingManager);
          loader.load("/models/FinalModels/Kris_1.gltf", function (gltf) {

            var Material = new THREE.MeshStandardMaterial({ color: 0xbcbcbc, roughness: 0.2, metalness: 0.8 });
            let Model = gltf.scene;
            Model.traverse((child, i) => {
              if (child.isMesh) {
                child.material = Material;
                child.material.side = THREE.DoubleSide;
              }
            });
            scene.add(Model);
          });

You can save the original material color in Material.userData. Whenever you want to switch to the original color value, you can just copy over this value to Material.color. Check out the following live demo:

Perfect! I solved it using an old example I found online but this is for sure the better solution and the way I was originally hoping to do it but couldn’t figure out how to store the data with userData. Thanks for clarifying!

1 Like