- Home /
The question is answered, right answer was accepted
Switching all Materials on objects using the same.
Newbie Question I guess but here goes:
GOAL:
Part 1: If a switch is activated switch Material 1 (Black) to Material 2 (White) and vice versa.
Part 2: Make sure this works for all objects the script is attached to.
So far it works for exactly 1 object in the scene e.g. Part 1 works, Part 2 doesn't.
I've the feeling I'm missing the obvious answer but after trying my luck for 3? hours I give up.
Anyway here's the code snippet.
{
public Material BlackMat;
public Material WhiteMat;
public Material PermanentMat;
public static bool switchActivated= false;
private string Material;
void Update () {
Material = renderer.materials[0].name;
if (switchActivated == true && Material == "White (Instance)")
{
renderer.material = BlackMat;
switchActivated = false;
}
else if (switchActivated== true && Material == "Black (Instance)")
{
renderer.material = WhiteMat;
switchActivated = false;
}
}
}
I do switch switchActivated to true only when the switch is being used. Which is being controlled from a different script.
Well, first you need to change your string variable's name because $$anonymous$$aterial is a keyword for Unity. As a matter of fact you should get an error with that. Secondly, you can change your material with
$$anonymous$$aterial White$$anonymous$$
$$anonymous$$aterial Black$$anonymous$$
gameObject.renderer.material = White$$anonymous$$; //(or Black$$anonymous$$)
using editors inspector to choose materials from file inspector.
$$anonymous$$aterial with an uppercase "$$anonymous$$" is only used as a declaration and can therefor be used as a variable name for a string. Though it's not exactly the "cleanest" way of coding... I blame late night coding fatigue for that ;)
Guess I need to clarify what's wrong in my original question: The script works as "intended" for 1 object in the scene. If the same object is duplicated a bunch of times it will still only work on the original one. I don't understand why this script will only work on one object and not on all the objects it is attached to.
I see. You might wanna keep the track of the objects in the scene as a list and go over them one by one like objects[0/1/2..].renderer.material or make a prefab and attach the script over it so every single object will work for on its own.
Answer by AracosDE · Sep 03, 2013 at 05:04 PM
Yeah so in case anyone else runs into the same issue:
"switchactivated == false" is being set immediately after the first material gets changed therefor all the others won't.
Guess this problem should be filed under: Wasting time by missing the obvious.