Archive for the ‘UI’ Category

Unity: Get UI element under mouse

Wednesday, March 30th, 2016

To check if the mouse is over any UI element you can use

EventSystem.current.IsPointerOverGameObject()

In case that function isn’t acting to your liking and you need to debug, or if you just want to know what object is under the mouse, you can use

PointerEventData pointerData = new PointerEventData(EventSystem.current) {
	position = Input.mousePosition
};

List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);

results.ForEach((result) => {
	Debug.Log(result);
});

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