- Home /
Change the color of the Unity 4.6 buttons in code
I'm looking to change the color of the buttons in my script, I would like the button to bed red when its not active and green when it is. I tried changing the color directly accessing the button itself but the editor told me to store it in a temporary variable. I have this so far:
var temp = button.colors.normalColor;
temp = Color.red;
if (button.enabled == true)
{
temp = Color.green;
}
else
temp = Color.green;
This doesn't change the button in my scene though, it stays the same default color. Can anyone lend a hand?
Answer by RandomUser123 · Sep 04, 2014 at 10:00 PM
Managed to figure it out, I was using the wrong properties. Instead of `button.colors.normalColor, you use the image property of the button like so:
if (button.enabled == false)
{
button.image.color = Color.red;
}
Hope this can help someone else :)
Answer by kacyesp · Sep 04, 2014 at 09:59 PM
Can you try this? Idk if you noticed but you left green as the color in both the if and the else block.
if (button.enabled == true)
{
button.colors.normalColor = Color.green;
}
else
button.colors.normalColor = Color.green;
The reason your original color didn't work is because you were only changing the value of temp, and not the value of normalColor. Since the type Color is a structure, values get copied over in assignments. If Color was a class rather than a structure, then temp would be a reference to normalColor and your code would have done what you expected.
Ha I never noticed that actually, I wasn't getting any color though unfortunately. I managed to sort it though, I was accessing the wrong properties, I have given an answer but thanks for the reply :)
You can't modify the return value of a property ('colors') so you'd have to:
var colors = button.colors;
colors.normalColor = some_color;
button.colors = colors;
Unity 5 doesn't accept the var keyword in functions, so there should be another way out
Incorrect, it does support var
anywhere. Been using var
everywhere since 4.5.