How to make button and slider color values reference a variable?

Hi,

I have several buttons and sliders. I want to change their colors based on the value of a global variable. Instead of looping through every single one and changing the color values each time, I am wondering if it is possible to make the color value a reference to a global value. That way I could just change the one global variable and all the sliders/buttons etc that reference that color variable would be updated.

Please let me know. Thanks

No, it is not since color is value type and buttons and sliders requres its own instances of colors. But you can create a script, reference a scriptable object containing color, and apply that color to your graphic objects at start and whenever it changes.

@palex-nx so I would have to create a list of the objects I want to change to that color, and loop through them everytime the color changes?

Nope. Colors are structs, so they’re copied by value, meaning that you can’t have a reference to the color. Whenever you say button.color = someColor;, the button gets a copy of the color.

The best way to do this is event-based. Whenever you set the color variable, raise an event to make all the button’s colors change.

public static class GlobalColorContainer {
    public static Color _globalColor;
    public static Color GlobalColor {
        get =>_globalColor;
        set {
            _globalColor = value;
            GlobalColorChanged(value);
        }
    }

    public static event Action<Color> GlobalColorChanged = delegate {}
}

// usage:

public class SetColorToGlobalColor : MonoBehaviour {
    [SerializeField] private Graphic target;

    private void Awake() {
        GlobalColorContainer.GlobalColorChanged += color => target.color = color;
    }
}

Absolutely correct.