How to bring back texture when I make material.map = null?

Hi gurus, I have a gltf models which have texture map on it(emmbeded). I create a button when clicking that button, all models goes to white material, like this:

var white = document.getElementById("white");
white.addEventListener("click", changeWhite);

function changeWhite() {
	if (scene) {
		scene.traverse(function (node) {
			if (node.isMesh) {
				node.material.map = null;
				node.material.needsUpdate = true;
			}
		})
	}
} 

but when I try to toggle it back, all texture map on that gltf models are gone.
So my question is, how to bring them back after I setting them all to null? Thanks

You will have to save a reference to the variable. If you delete the references that three.js gives you, they are gone. For example:

node.material.userData.originalMap = node.material.map;
node.material.map = null;
1 Like

Thank you Sir, it’s working very well…
I have a small question for that toggle button, I already know it can toggle mesh visible by this node.visible = !node.visible; but I don’t know how to toggle the “original map” and the new “white material” for just “one” button… do you think it’s possible? many thanks

In the handler, check the toggle state for that mesh. The easiest and least ambiguous way is to store a boolean that tells whether you have removed the map or not (since this boolean is initially undefined, which evaluates to false, I would recommend having the boolean true mean that the map has been removed). Remember to change flip that boolean whenever you toggle the state. Then do an if…else on the boolean in the handler.

1 Like

@ EliasHasle Sorry for the stupid question, I solved it for this, not sure if this is looking stupid(and long…) but this code works for a toggle event:

if (scene) {
		scene.traverse(function (node) {
			if (node.isMesh) {
				if (node.material.map == null) {
					node.material.map = node.material.userData.originalMap;
					node.material.needsUpdate = true;
				} else {
					node.material.map = null;
					node.material.needsUpdate = true;
				}
			}
		})
	}

That will work if all meshes in the scene had a map to begin with, but perhaps fail when some meshes had no map to begin with. See my recommendation above.

Oh you are right… I do have some materials that don’t have map at all. Thank you Sir, I learned a lot… and thank you for helping a noob like me ^^