I’m trying to check if the mouse pointer is over any UI element in the scene. I have lots of UI around the edges, and just the main camera’s view in the center, so I want to prevent certain actions if the mouse is over UI. Seems simple enough!
For the longest time, I’ve been using this snippet that I found online. I did a bunch of other digging and it seems like the most straightforward approach, but after looking in the profiler… it’s not the most efficient.
I would appreciate any and all help fixing this up!
public static bool IsPointerOverUIObject()
{
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}
This is in a HelperMethods class and I use it in a simple if statement in an Update loop before running code. This only happens in one update loop throughout my project. It seems like all the strain is on the Raycasting being done here, which is understandable, but is there any other way of doing this?
All my UI is on the UI Layer, if that matters.
This is the Input section of the forums, this should be posted to the UI section.
This is already built in and doesn’t need this method, it already knows if the mouse is over a GameObject that uses the EventSystem so it’s much faster than a raycast.
if (EventSystem.current.IsPointerOverGameObject())
{
}
I apologize, I thought it would be under Inout because of event systems and such.
In any case, thanks for the reply! From my understanding IsPointerOverGameObject will return true even over a 3d object in the scene, which makes it unusable in this case. Am I wrong?
It will only register objects that are part of the event system. Which is anything that has implemented any of the event handler interfaces in the UnityEngine.EventSystems namespace.
Yes it can register 2D/3D objects in the scene but only if an attached script has implemented one of the event handler interfaces and the camera has a physics 2D/3D raycaster component on it.