Unity: Is mouse (or any coordinates) within UI element’s rect

Here’s a quick way to check if the mouse or any other coordinates are within any UI object’s boundaries.

This method doesn’t use raycast so it ignores all overlapping objects, it works just like ActionScript’s object.HitTest(coords) function.

public bool AreCoordsWithinUiObject(Vector2 coords, GameObject gameObj)
{
	Vector2 localPos = gameObj.transform.InverseTransformPoint(coords);
	return ((RectTransform) gameObj.transform).rect.Contains(localPos);
}

// Example usage
bool isMouseOverIcon = AreCoordsWithinGameObject(Input.mousePosition, _myUiIcon);

Tags: , , , , , ,

2 Responses to “Unity: Is mouse (or any coordinates) within UI element’s rect”

  1. Random Unity Hobbyist Says:

    Just what I was googling for. Thank you internet stranger!

  2. KnightOwl Says:

    Thanks for this, it works for 3D as well. I’m using it to check where a UI item is being ‘dragged’ and checking if there is another specific UI ‘slot’ element underneath:

    bool slotted = false;
    foreach (MaterialSinkSlot slot in slots)
    {
    Vector2 localPoint = slot.transform.InverseTransformPoint(transform.position); //transform.position is a Vector3, z-coord is lost when converting to Vector2
    if ((slot.transform as RectTransform).rect.Contains(localPoint))
    {
    slot.Accept(this);
    slotted = true;
    break;
    }
    }