- Home /
Changing material of an object
Hi. I looked for a solution to this but couldn't find anything. What i want to do is change the material of an object every few seconds. Here is my code:
private float countdown;
public float originalCountdown;
public Material white, black;
void Start () {
countdown = originalCountdown;
}
void Update() {
countdown -= Time.deltaTime;
if (countdown <= 0) {
Change ();
}
}
void Change() {
countdown = originalCountdown;
if (renderer.material = black) {
Debug.Log ("White");
renderer.material = white;
} else if (renderer.material = white) {
Debug.Log ("Black");
renderer.material = black;
}
}
}
What is happening now is that the material changes from black to white and i receive the message "White". Then the material stays white and i keep receiving the message "White" every time that Change() is called.
I really can't understand what is bad with the code. Also i am not using == because it only works with =. Not sure why.
Pretty new to all this anyway.
Answer by robertbu · Apr 27, 2014 at 11:42 PM
For comparison operations, you need to use double equals ('=='). In addition, since you are switching, you don't need the else:
void Change() {
countdown = originalCountdown;
if (renderer.material == black) {
Debug.Log ("White");
renderer.material = white;
}
else {
Debug.Log ("Black");
renderer.material = black;
}
}
Now i receive the message "Black" and it never changes from black to white.
Single '=' is definitely not the right way to solve your issue. I'm guessing that something is changing the material instance which means the material, though black, will not evaluate to the material you assigned. You can use a boolean ins$$anonymous$$d. At the top of the file:
private bool isBlack = false; // Set for original color.
Then the code changes to:
void Change() {
countdown = originalCountdown;
if (isBlack) {
Debug.Log ("White");
renderer.material = white;
}
else {
Debug.Log ("Black");
renderer.material = black;
}
isBlack = !isBlack;
}
Your answer
Follow this Question
Related Questions
Material doesn't have a color property '_Color' 4 Answers
Change material with UI button ? 0 Answers
memory consumption when changing materials [iOS] 2 Answers
Changing two different objects renderer colour 1 Answer
how to switch material with script? 1 Answer