'IsPointerOverGameObject always returns false for touch

IsPointerOverGameObject always returns false for touch. I have tried all solutions that I could find.

It works perfectly in Editor - clicks are blocked from falling through UI, but no a mobile this method always returns false.

Here is my code:

private static bool IsPointerOverGameObject()
    {
        bool isPointerOverGameObject = EventSystem.current.IsPointerOverGameObject();

        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch touch = Input.touches[i];
            if (touch.phase != TouchPhase.Canceled && touch.phase != TouchPhase.Ended)
            {
                if (EventSystem.current.IsPointerOverGameObject(Input.touches[i].fingerId))
                {
                    isPointerOverGameObject = true;
                    break;
                }
            }
        }

        return isPointerOverGameObject;
    }

public void OnMouseDown()
{
    if (IsPointerOverGameObject())
    {
        return;
    }

    // code
}


Solution 1:[1]

This fix works from me:

 private 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;
 }

Got it from: http://answers.unity.com/answers/1115473/view.html

Solution 2:[2]

According to the unity's help forum here.

The EventSystem.current.IsPointerOverGameObject() requires the touch id in the parameter to be passed. Try to pass Input.touches[i].fingerId as the parameter for it work in mobile devices and for the editor you need to leave it empty.

Try this EventSystem.current.IsPointerOverGameObject(Input.touches[i].fingerId)

edit: My bad, I didn't see that you already were passing the touch id in the code I saw the first line and thought that was missing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayadev Haddadi
Solution 2 Community