Posts Tagged ‘HitTest’

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

Monday, March 30th, 2015

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);