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);
June 25th, 2016 at 13:55
Just what I was googling for. Thank you internet stranger!
June 10th, 2018 at 07:58
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;
}
}