Simple Button Problem

What do i need to add so when a button is clicked, it opens a menu, and when clicked again closes it. I know i could use two vars, one setting to true, and one false, and vice versa. But what’s the more elegant solutions.

You could use a single boolean.
Example:

private bool menu = false;

void OnGUI()
{
        if(GUILayout.Button("Menu"))
        {
                menu = !menu;
        }
}

Thank You. Exactly what i ment.

Ok, To add onto this, How do i disable a button? Like so it is still there but you cant click on it. Is there a API reference to this?

to disable the button you would probally have to emulate with a box, or make it so you can still click it and nothing will happen (use a bool), unfortunatly i only know JS. so heres an example in js:

in JS:

now if you were to toggle allow use the button could not be used.

(had to quote wouldn’t let me use script brackets :S

@mattcscz: that’s because the tag is called ‘code’ not ‘script’ :slight_smile:

@TheCowMan: The Unity GUI controls don’t have a ‘disabled’ render state unfortunately. You could do something like mattcscz describes, but unfortunately the button would still react as if it were active (i.e. it would look like it was being clicked even though it wouldn’t do anything). Slightly better would be to use GUI.Label, GUI.Box, or some other non-reactive GUI control but pass in the “button” GUIStyle; you’d get a control that looks like a regular button, but doesn’t react when clicked.

The right way to do it, though, would be to combine that with a custom GUIStyle that made the button look visibly different, in order to provide the user an affordance of non-interactivity.

OK. thanks for the help!

@ laurie, yes but you cannot access the “code” box in quick reply and it would’nt let me go to the other reply method… so i just used quotes…

What I have been doing to disable any GUI components is utilizing GUI.enabled.An example would be:

var isButtonEnabled = true;
function OnGUI ()
{
   GUI.enabled = isButtonEnabled;
   if (GUILayout.Button("Button Text"))
    {
          // Do something here
    }
   GUI.enabled = true;
}

Essentially what this accomplishes is any GUI components drawn while GUI.enabled == false will be rendered in a disabled state and will not respond to user input.

I don’t know how I’d missed that, thanks for pointing it out! :slight_smile: