- Home /
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?
Answer by aldonaletto · Feb 07, 2012 at 01:21 AM
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 } }
I've ended up using the buttons Rect.contains(Event.current.mousePosition) ins$$anonymous$$d.
Would it be usefull to split the contains in two if, so you check the x first, and the y only if you pass the x ? If there is a lot of buttons I mean, and if you aim at a device without much power.
@Berenger, I suppose the Unity function Rect.Contains does something like this, but probably in C++ compiled to native code, which is much faster than anything we can write in scripts.
Our scripts are compiled to CIL, a kind of interpreted assembler with superpowers. Unfortunately, super-speed isn't among these superpowers: the interpretation process and other house keeping jobs eat precious CPU cycles.
@Tsanas, good alternative: Event.current.mousePosition is Input.mousePosition in the GUI "upside-down-Y" fashion, thus there's no need to invert Y.
Your answer
Follow this Question
Related Questions
Pause Button Problems 2 Answers
Close my GUI button by repressing the same Hot-key. 3 Answers
How to assign a different tooltip to each GUI button? 0 Answers
Navigating GUI with gamepad on GUI.Toggle 0 Answers
C# Multiple GUI.Tooltips 2 Answers