# 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. Oddly, 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;
}
}

• @AlexandreVaillancourt oh, sure. I think i was supposed to wait a while before it was possible to accept, but i forgot about it haha. – DragonautX Feb 15 '17 at 2:17
• Yeah, I guess that it's probably what happened :) Thanks! – Vaillancourt Feb 15 '17 at 2:38