EventSystems: how to detect if the mouse is over UI elements?

When the player clicks on a UI element I don’t want a building to appear so I need a sort of
IsPointerOverUIElement()
but this function doesn’t exist
what’s the recommended way to do that?

1 Like

Try this:

    public static bool IsPointerOverUIElement()
    {
        var eventData = new PointerEventData(EventSystem.current);
        eventData.position = Input.mousePosition;
        var results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventData, results);
        return results.Count > 0;
    }
10 Likes

This doesn’t work. Just like the built in function IsPointerOverGameObject(), it’s also true when it’s over a gameobject with a collider, not just UI elements.

So you have to filter the results by layer (assuming all of your UI elements are on a layer)

return results.Where(r => r.gameObject.layer==<UI LAYER NUMBER>).Count() > 0;

You could optimise that with a firstordefault so that it exists as soon as it finds one

4 Likes

Building on what others have mentioned, this also worked for me:

var eventData = new PointerEventData(EventSystem.current);
eventData.position = Input.mousePosition;
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);

// Expose this as a variable in your script so other components can check for it.
isPointerOverUI = results.Count(x => x.gameObject.GetComponent<RectTransform>()) > 0;
2 Likes