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: , , , , , ,

One Response 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!

Leave a Reply