- Home /
How to change a buttons color?
im having trouble setting the color of a button I want when the player money is less than the invest cost then I want the button to be gray and the interaction turned off. But when I change the colors the button image completely disappears but the color of the button in the inspector is the same as the one I set in the code, just I cant see it because the Image is gone.
public Button investButton;
public ColorBlock investButtonColor;
void Update()
{
if (tap.money >= investCost)
{
investButton.colors = investButtonColor;
investButtonColor.highlightedColor = Color.yellow;
investButtonColor.normalColor = Color.yellow;
investButtonColor.pressedColor = Color.yellow;
}
else
{
investButton.colors = investButtonColor;
investButtonColor.highlightedColor = Color.cyan;
investButtonColor.normalColor = Color.cyan;
investButtonColor.pressedColor = Color.cyan;
}
}
Answer by Oziry · Dec 27, 2016 at 10:24 AM
perhaps something like :
investbutton.GetComponent<Image>().color = Color.yellow;
And 4 years later, you've just saved a random guy! Thank you so much. The colors property from Button component doesn't work fine at all, it is really buggy.
Still saving people's butts, Oziry. Also, as a helping hand to future seekers of this knowledge, I ran across this problem when setting the colors for this using the color picker: https://answers.unity.com/questions/908438/buttoons-become-invisible-when-changing-color-on-b.html
Actually OP had the right idea but incorrect sequence. You need to change the values in the ColorBlock first and THEN assign. The button component presumably copies these values so it's not an assignment per-say.
investButtonColor.highlightedColor = Color.yellow;
investButtonColor.normalColor = Color.yellow;
investButtonColor.pressedColor = Color.yellow;
investButton.colors = investButtonColor;
See the following thread: https://answers.unity.com/questions/1401626/how-to-change-button-color-highlited-color-etc.html
Answer by karlaa15655 · Feb 04, 2018 at 10:52 PM
I used this: public void TaskOnClick1() { GameObject buttonclr = GameObject.Find("Button1"); buttonclr.GetComponent().color = Color.magenta; } You have to find the button with you want to work with, so instead of "Button1" put the name of your button After that, you have to assign the void to the button
Your answer
Follow this Question
Related Questions
Getting number of seconds a user has been in game 2 Answers
UI text color not assigning correctly 2 Answers
Xbox Controller and Unity Buttons UI 0 Answers
Make image follow your cursor 1 Answer
Trouble with ZXing QR Scanning 0 Answers