I'm trying to add GUI elements to a scene where I do Raycasting to select objects. But everytime I click a button, I am still raycasting. I would like to use an approach outlined in another question using the GUI.tooltip object.
This approach doesn't work for me in Unity 3.0.0f5 The following C# Script will always print "got here" whether the cursor is over a GUI element or not. Am I doing something obviously wrong with this approach?
public class TestScript1 : MonoBehaviour
{
void OnGUI()
{
Rect boxRect = new Rect (10, 350,150,200);
GUI.Button (boxRect, new GUIContent("Box Header", "BoxTooltip"));
}
void FixedUpdate ()
{
if (Input.GetMouseButtonDown(0) && GUI.tooltip == "")
{
print("got here.");
}
}
}
I hate to provide an answer to my own question, but I wanted to share what I've found.
It seems my error here is that I assumed GUI.tooltip would be persisted outside of the OnGUI function. This does not appear to be the case, so I don't think we can rely on it in an Update() function, much less in another class.
My current solution is to use the following classes:
A static GUIManager class to save the state of whether the mouse is currently over a GUI element.
In any GUI Script, add some code to check the Tooltip (or hit test a texture or whatever code you want), and set the global static variable on my GUIManager. Using this approach, I can then check to see whether GUIManager.MouseOverGUI == true when determining whether I want to raycast or not. If anyone sees a flaw, feel free to contribute.
EDIT: Fixed the code to work with scenes that have multiple scripts implementing OnGUI(). Be sure to attach GUIManager to your GUI object so LateUpdate() gets executed to reset the MouseOverGUI bit prior to the OnGUI() logic.
public class GUIManager : MonoBehaviour
{
public static bool MouseOverGUI = false;
void LateUpdate()
{
MouseOverGUI = false;
}
}
public class TestScript1 : MonoBehaviour
{
void OnGUI()
{
Rect boxRect = new Rect (10, 350,150,200);
GUI.Button (boxRect, new GUIContent("Box Header", "BoxTooltip"));
if (GUI.tooltip != "")
GUIManager.MouseOverGUI = true;
}
void Update()
{
if (Input.GetMouseButtonDown(0) && !GUIManager.MouseOverGUI)
{
print("got here.");
}
}
}
Im trying to do some GUI and need exact same functionality.
Thou im having problem with the MouseOverGUI to be reseted before I press the button to false,
its more like blinking true/false really fast. If im lucky and press at the exact right time i would get the MouseOverGUI = true.
Thanks man! That what’s exactly what I was seaching for. I’ve two days already trying to figure out how to check a mouse click and having a tooltip at the same time. And this give me the result I needed. Thank you very much!