- Home /
How to toggle the color of a button?
Hello,
I wonder if it is possible to make a button toggle its color. Any ideas how to do it?
Thank you in advance.
Answer by duck · Mar 09, 2010 at 08:53 PM
If you're doing this with the new OnGUI system, and you specifically want it to look like a Button, and not a Toggle, you'll need to make a GUI.Toggle, but tell it to use the 'button' style from your custom GUISkin. It would end up looking something like this...
In C#
public GUISkin guiSkin; public bool toggleBool = false; Rect toggleRect = new Rect(10, 10, 150, 100);
void OnGUI() { toggleBool = GUI.Toggle(toggleRect , toggleBool, "Hi!", guiSkin.button);
}
Or in Javascript
var guiSkin : GUISkin; var toggleBool = false; private var toggleRect = Rect(10, 10, 150, 100);
function OnGUI() { toggleBool = GUI.Toggle(toggleRect , toggleBool, "Hi!", guiSkin.button);
}
And if you want your buttons to change colour when active, you'll need to use a custom GUISkin. In it, customize the "Normal", "Hover" & "Active" button states to show your inactive colour, and customize the "On Normal", "On Hover", and "On Active" button states to show your active colour.
You can only assign textures as far as I can tell, so the only way to assign a colour is by creating a texture of the desired colour, and using that.
Hope this is enough to get your toggle working as you want it!
@Duck, yes, it's a good answer :) But I have to say, so far the GUI system is bugging me. There's no way to set a Button.enable property, for instance. So if I want to have exactly one button of three active, I need a Boolean array and change it based on which button is clicked. Ah well...
I'm doing this for multiple toggle buttons, and the last one retains the OnHover texture, whether it's supposed to be on or off and no matter where the cursor is.
The C# example gives a NullReferenceException
. Just telling because you asked in your profile. ;)