Change colors of UI button via script

You have to change the colors not the normalColor. The GetComponent<Button>().colors returns ColorBlock.

So, create a new instance of ColorBlock. Modify normalColor from that ColorBlock then assign that ColorBlock to the GetComponent<Button>().colors.

Full example:

ColorBlock colorBlock = new ColorBlock();
colorBlock.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);

prev.GetComponent<Button>().colors = colorBlock;

This will overwrite your other color settings. To preserver them, create your ColorBlock from prev.GetComponent<Button>().colors;

ColorBlock colorBlock = prev.GetComponent<Button>().colors;
colorBlock.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);

prev.GetComponent<Button>().colors = colorBlock;

You can also modify the color properties below:

colorBlock.pressedColor = new Color(1f, 0.0f, 0.0f, 1.0f);
colorBlock.highlightedColor = new Color(0f, 1f, 0.0f, 1.0f);
colorBlock.disabledColor = new Color(0f, 0f, 1, 1.0f);

Leave a Comment