How to check if player is hovering mouse over a GUI Box

Hey guys,

I was wondering, is it possible to simply check if the user is hovering their mouse over a gui box?

Thanks

-Grady

If you want to use a GUI Box or any other OnGUI element whose position and size is defined by a Rect, you need to realise that GUI elements are in GUI coordinates (0,0 = top-left), where Input.mousePosition is in Screen, or pixel coordinates (0,0 = bottom-left). This means you can do one of two things.

The first solution is the easier of the two - Events. Events and OnGUI are very tightly connected, so they share the same coordinate system.

var mousePosFromEvent : Vector2 = Event.current.mousePosition;

The second solution, if you for some reason don’t want to use events, is to flip the y axis of Input.mousePosition.

var mousePosInGUICoords : Vector2 = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);

You can read about Input.mousePosition here. Or read more about Events here and here.

(thanks for robertbu for pointing out that pixel and gui coords don’t match.)

function OnGUI () {

    var rect1 : Rect = Rect(240,240,320,150);
    var rect2 : Rect = Rect(0,0,300,500);
    
    GUI.Box(rect1, "Rect1");
    GUI.Box(rect2, "Rect2");
    
    if(rect1.Contains(Event.current.mousePosition))
    	Debug.Log("rect1");
    else if(rect2.Contains(Event.current.mousePosition))
    	Debug.Log("rect2");
    else
    	Debug.Log("no rect");
}

If you don’t mind using GUITextures, you can use the MonoBehaviour.OnMouseEnter() function.

function OnMouseEnter () {
   print("There is a mouse on me!");
}

– David

There is what you need here in the Unity guide: Rect.Contains. Example:

`//Check if the mouse is inside a Rect  
var mouseInside = false;
function Update () {
    var rect = Rect (0, 0, 150, 150);
    if (rect.Contains(Input.mousePosition))
        mouseInside = true;
    else
        mouseInside = false; 
}
`

Just use a Rect wich represents your GUI box and you are done.

I had to solve an issue like this today. I thought I would post my answer here so help others out…

On MouseEnter start a coroutine that waits whatever you want for a hover delay. Once the coroutine expires process your OnHover task; starting with a check to see that the mouse is within the rect before continuing. This will make sure we are still hovering as the timer expires. Upon MouseExit stop the coroutine.

 float hoverDelay = 5;
 Rect rectIcon; // The Rect for the GUI.Texture we are hovering over.
    
void OnMouseOver ()
{
	StartCoroutine( "Wait", hoverDelay );
}
    	
void OnMouseExit ()
{
	StopCoroutine("Wait");
}
    	
private IEnumerator Wait (float seconds)
{
	yield return new WaitForSeconds(seconds);
		if (rectIcon.Contains (Input.mousePosition)) {
			//Do OnHover Stuff here. Or set a bool to trigger an event elsewhere.
   	}
}