Changing the color of a button in script?

I have searched for this for about 20 minutes now after failing to do it myself and still got no-where.
I have tried things like:

button.colors.normalColor = color;
button.colors.normalColor = new Color (0.0f, 0.75f, 1f, 1f);

etc but nothing works, I just keep getting the same error in Unity which no-one else seems to get:

error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Selectable.colors'. Consider storing the value in a temporary variable

This is because colors is a struct and so its returning a copy(value type) which you then apply the normal color to, the compiler is stopping you from writing buggy code.
Make a copy, apply the change and then apply the copy back.

ColorBlock cb = button.colors;
cb.normalColor = new Color(0.0f, 0.75f, 1f, 1f);
button.colors = cb;
3 Likes

The example code on the ColorBlock.normalColor documentation page should probably be updated:

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.

public class ExampleClass : MonoBehaviour
{
    public Button button;
    public Color newColor;

     void Start ()
    {
        //Changes the button's Normal color to the new color.
        button.colors.normalColor = newColor;
    }
}
1 Like

[[quote=“TonyLi, post:3, topic: 591325, username:TonyLi”]
The example code on the ColorBlock.normalColor documentation page should probably be updated:

using UnityEngine;
using System.Collections;
using UnityEngine.UI; // Required when Using UI elements.

public class ExampleClass : MonoBehaviour
{
    public Button button;
    public Color newColor;

     void Start ()
    {
        //Changes the button's Normal color to the new color.
        button.colors.normalColor = newColor;
    }
}

[/quote]
](http://forum.unity3d.com/threads/changing-the-color-of-a-button-in-script.344121/reply?quote=2227110)

Yep thanks for pointing it out we will fix it :sweat_smile: