GUI toggle on click, unless on GUI.

Hi there.

Im having a hard time creating a simple gui toggle.

I want the GUI to toggle between on/off when the player clicks anywhere on the screen, UNLESS the click is on the GUI.

Im using tooltips to know whenever the mouse is over a gui-element, but the problem seems to be that during the actual click, the tooltip is null. Even when the mouse is still over the gui.

This is what i have so far:


private string currentTooltip = "";

void Update ()
{
    if (string.IsNullOrEmpty(currentTooltip))
    {
        if (Input.GetMouseButtonDown(0))
        {
            DisplayBunkerGUI = DisplayBunkerGUI ? false : true;
        }
    }
}

void OnGUI()
{
    if (DisplayBunkerGUI)
    {
         GUI.Button(new Rect(50, 50, 100, 100), ToolTipEnter);
    }

    currentTooltip = GUI.tooltip;
}

So when i click outside the button, the GUI toggles fine, but when I click on the button, the GUI still toggles.

Anyone got any suggestions?

A simple way to avoid the button area is to use buttonRect.Contains(Vector2 point) : it returns true when the rect contains the specified point. There’s a trick, however: GUI Y is upside down, thus we must convert the mouse position Y to have meaningful results

Rect rButton = new Rect(50, 50, 100, 100); // define button rect

void Update(){
  if (Input.GetMouseButtonDown(0)){
    bool inButton = false;
    if (DisplayBunkerGUI){ // if button is being displayed...
      Vector2 mPos = Input.mousePosition; // check button area:
      mPos.y = Screen.height - mPos.y; // transform Y to GUI space...
      inButton = rButton.Contains(mPos); // check if mouse inside button rect
    }
    if (!inButton){ // if not over button...
      DisplayBunkerGUI = !DisplayBunkerGUI; // toggle variable
    }
  }
}

void OnGUI(){
  if (DisplayBunkerGUI){
    GUI.Button(rButton, ToolTipEnter); // use rButton to draw the button
  }
}