- Home /
Material Color Won't Change On Input
Ok, so I have been working on a simple mobile game. Right now I am making the script around PC (for ease of testing). The problem is that when ever I try to change the cube's color, it will change once, but from then on the material color won't change. I have experimented with different colors and different materials, but the cube's material color never changes. Here is my script (NOTE: The script isn't just for the material's color change, but also for some physics, as I will need to incorporate both together later, if this changes anything):
#pragma strict
var jumpForce = 10;
var jumping = false;
var isGrounded = true;
var jumpValue = 0;
function Start() {
renderer.material.color = Color.blue;
}
function Update () {
if(Input.GetKeyDown(KeyCode.Space) & isGrounded) {
isGrounded = false;
rigidbody2D.velocity = new Vector2(0, jumpForce);
}
if(Input.GetKeyDown(KeyCode.Q) && renderer.material.color == Color.red) {
renderer.material.color = Color.blue;
print ("called");
}
if(Input.GetKeyDown(KeyCode.Q) && renderer.material.color == Color.blue) {
renderer.material.color = Color.red;
}
transform.rotation = Quaternion.identity;
}
function OnCollisionEnter2D (other : Collision2D) {
isGrounded = true;
}
Answer by maccabbe · Dec 29, 2015 at 05:06 AM
The issue is that the color switches from red to blue and immediately back to red.
If the color is red then
if(Input.GetKeyDown(KeyCode.Q) && renderer.material.color == Color.red) {
renderer.material.color = Color.blue;
print ("called");
}
Gets called and the color is set to blue.
The color is now blue so when the next statement is run
if(Input.GetKeyDown(KeyCode.Q) && renderer.material.color == Color.blue) {
renderer.material.color = Color.red;
}
the color is immediately set back to red.
There should be an if/else if/else, i.e.
if(Input.GetKeyDown(KeyCode.Q) && renderer.material.color == Color.red) {
renderer.material.color = Color.blue;
print ("called");
}
else if(Input.GetKeyDown(KeyCode.Q) && renderer.material.color == Color.blue) {
renderer.material.color = Color.red;
}
Thanks a lot! Turns out that when I called the function, they were being called on the same frame due to it switching (the color was red, but since it is now blue, it goes back to red because it all occurred at the same frame). Never thought of using an else if statement though. Thanks a bunch anyways!
Your answer
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
Material doesn't have a color property '_Color' 4 Answers
Massive FPS hit when changing colors on the fly 3 Answers
When changing the color of an instantiated object, I keep getting an error - how do I fix this? 0 Answers
render.material.color is not working, or at least not completely? 1 Answer