- Home /
How to change Normal color, Highlighted color etc. in 4.6 buttons with code
The new 4.6 buttons have options for Highlighted color, Normal color, Pressed color, Disabled color. I want to change those with code.
When I try something like
tempButton.GetComponent<Button>().colors.normalColor = Color.red;
I get an error: Assets/2-scripts/LevelSelectMenuScript.cs(32,49): error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Selectable.colors'. Consider storing the value in a temporary variable
When I try something like
tempButton.GetComponent<Button>().image.color = Color.red;
I get a weird mix of the image color (from the image component) and the normal color (from the button component)
Any ideas on how to do it right?
If you make variables public so you can everything including ColorBlock, you can see normalColor getting changed in your script (via the inspector,) but not in the Button component itself. It's like you are basically instantiating a new ColorBlock in your script rather than getting a reference to the one on the Button component. Not understanding why this is happening. Is this a bug?
Answer by PeterMu · Sep 30, 2014 at 11:05 PM
Ahh - I had exactly this question. The hint you provided got me moving.
I found that:
Button b = rButton.GetComponent<Button>();
ColorBlock cb = b.colors;
cb.normalColor = Color.white;
b.colors = cb;
does the trick. (rButton is the Button game object.)
Ant this is so stupid! Y, it worked, but why we have to make 4 lines ins$$anonymous$$d of 1? I'm java developer, so I wonder? Cause clearly I see:
[Serializable]
public struct ColorBlock
{public Color normalColor
{
get
{
return this.m_NormalColor;
}
set
{
this.m_NormalColor = value;
}
}
}}
Why I cant use this set? Is it a unity infirmity or c#?
@Sarseth The reason this doesn't work (I think) is because ColorBlock is a struct and it's passed by value, not by reference, so you're essentially trying to modify a non-referenced copy of the struct.
Your answer
Follow this Question
Related Questions
Sorting the children of a Grid Layout in 4.6 UI 3 Answers
[4.6 - UI] Force GUI to render on top 1 Answer
Move gameobject to button in new 4.6? 0 Answers
Infinite ScrollRect? 1 Answer
4.6 UI transfer between Menu pages 2 Answers