How can I change the highlighted color of a Unity button when it's clicked?

I was playing around with buttons in Unity, and I wanted to see if I could change a button’s highlighted color every time I clicked on it. I added a script in the same GameObject as a button component, and I had a changeColor function attached to the component’s OnClick(). The function was in a ButtonScript class written like this:

public class ButtonScript : MonoBehaviour {
	public Button button;

	public void changeColor() {
		Debug.Log ("Changing highlighed color");
		int r = Random.Range (0, 255);
		int g = Random.Range (0, 255);
		int b = Random.Range (0, 255);
		Color currentColor = button.colors.highlightedColor;
		currentColor.r = r;
		currentColor.g = g;
		currentColor.b = b;
	}
}

I couldn’t do button.colors.highlightedColor = new Color(r,g,b); because I got a “Consider storing the value in a temporary variable” error. When I tried a test play and clicked the button multiple times, the highlighted color didn’t change. How can I make a function that changes a button’s highlighted color when it’s clicked, if it’s possible?

I found that I needed to reassign currentColor to button.colors.highlighted afterwards. I couldn’t do button.colors.highlightedColor = currentColor, but I could reassign to the ColorBlock that button.colors returns (I got the idea from @vexe’s comment here). I also saw that the Color constructor takes floats from 0 to 1, not ints from 0 to 255 (even so, should’ve been Random.Range(0,256). Here’s the class that worked for me:

public class ButtonScript : MonoBehaviour {
	public Button button;

	public void changeColor() {
		Debug.Log ("Changing highlighed color");
		float r = Random.Range (0f, 1f);
		float g = Random.Range (0f, 1f);
		float b = Random.Range (0f, 1f);
		ColorBlock colorVar = button.colors;
		colorVar.highlightedColor = new Color (r, g, b);
		button.colors = colorVar;
	}
}
1 Like

@DragonautX solved my problem, which was a little bit differente, but I only needed this:

ColorBlock colorVar = button.colors;
colorVar.highlightedColor = new Color (r, g, b);
button.colors = colorVar;

(Obiously with a value for r, g b)

The problem in my case was that I wasn’t able to modify directly colors.highlightedColor because Unity told me that it wasn’t a variable. So I just had to modify colors directly, in the way @DragonautX showed.

Just get colors to a ColorBlock variable, modify that variable, and then assign colors’ value to that variable.

I know this is not the same problem that was originally posted, but I found this question trying to fix my problem, so I hope this can help someone who ends up here just as me.