Search code examples
c#unity-game-enginetouch

In Unity3d, How to detect touch on UI, or not?


I am making a Unity3d mobile application. And I have a problem: How to detect touch on UI, or not?

I tried this (but it doesn't work):

UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject();

and this:

private static List<RaycastResult> tempRaycastResults = new List<RaycastResult>();

public bool PointIsOverUI(float x, float y)
{
    var eventDataCurrentPosition = new PointerEventData(EventSystem.current);

    eventDataCurrentPosition.position = new Vector2(x, y);

    tempRaycastResults.Clear();

    EventSystem.current.RaycastAll(eventDataCurrentPosition, tempRaycastResults);
    
    return tempRaycastResults.Count > 0;
}

Solution

  • For mobile you need to pass the id of the Touch to IsPointerOverGameObject

    foreach (Touch touch in Input.touches)
    {
        int id = touch.fingerId;
        if (EventSystem.current.IsPointerOverGameObject(id))
        {
            // ui touched
        }
    }