- Home /
Detect Color in "If" Statement
Hi, I´m trying to make a system in which I detect the color of a platform I hit, but it doesn't seems to work, how can I detect var + renderer.material.color?
Code:
void FixedUpdate () {
if(touchingPlatform && renderer.material.color(210,2,2)){
transform.localPosition = startPosition;
}
}
Answer by greenshadow · May 13, 2013 at 02:30 AM
I am pretty sure that statement is just going to set the color, not compare it. You might try something like this:
Color myColor = new Color(210f, 2f, 2f, 1f);
if(touchingPlatform && renderer.material.color == myColor){
transform.localPosition = startPosition;
}
Thanks for the reply, but it isn't working, it doesnt detect when I touch something of that color. Have a nice day :)
Ahh.. of course. I forgot, Unity does not use a scale of 0-255 for it's RGBA scheme; it converts them to a value between 0.0 and 1.0 (with 1.0 equaling 255). For example, I have a blue object in a scene. The Unity RGBA value for this is (0f, 0f, 1f, 1f). In the update method for the attached script, I execute this check:
Color myColor = new Color(0f, 0f, 1f, 1f);
if (this.gameObject.renderer.material.color == myColor) {
//Works every time the object is blue
}
This triggers just fine. To really make sure you are making the proper comparison, you should have that color stored in a variable when you assign it to an object. You also need to make sure you are accessing the renderer of the correct gameObject. Then you can make the comparison like so:
if(touchingPlatform && gameObject.renderer.material.color == myStoredColor){
}
Thanks, it WOR$$anonymous$$S! :) Now I can move on in my project, thanks for the quick replies and the excellent feedback. Have a nice day :)
Answer by AlucardJay · May 13, 2013 at 04:20 AM
The values of the Color variable are between 0 and 1, not 0 and 255 :
http://docs.unity3d.com/Documentation/ScriptReference/Color.html
Each color component is a floating point value with a range from 0 to 1
Apart form that, greenshadow is correct, you want to check if your renderer is equal to somthing :
if ( touchingPlatform && renderer.material.color == Color(210,2,2) ) {