- Home /
The question is answered, right answer was accepted
MeshRenderer.material.color not changing inside if statement but is outside if statement?
My problem is simple. I want a GameObject that will change color if you click it once, and change back if you click it again. Here is my code:
if (Input.GetButtonUp ("Select")) {
// A tile has been clicked!
MeshRenderer hitRenderer = mouseRayHit.GetComponentInChildren<MeshRenderer> ();
if (hitRenderer.material.color == Color.red) {
hitRenderer.material.color = Color.white;
}
hitRenderer.material.color = Color.red;
}
If I click it once, it will change to red, but it will not change back to white. This is confuzzling me very much. Is there some obscure thing about changing colors of instances of materials?
Answer by Bunny83 · Jan 03, 2018 at 01:41 PM
Uhm you unconditionally set the color to red at the end. So whenever this code snippet runs you always set the color to red. You probably want something like this:
if (Input.GetButtonUp ("Select"))
{
MeshRenderer hitRenderer = mouseRayHit.GetComponentInChildren<MeshRenderer> ();
if (hitRenderer.material.color == Color.red)
{
hitRenderer.material.color = Color.white;
}
else
{
hitRenderer.material.color = Color.red;
}
}
I just tried that before reading this and it worked and I was co$$anonymous$$g back here to close this question and then saw you had beat me. GG
Follow this Question
Related Questions
Material doesn't have a color property '_Color' 4 Answers
Changing two different objects renderer colour 1 Answer
Changing Material Color Via Script 1 Answer
Adjust tint color of particles/additive? 2 Answers
Lights colored like material 0 Answers