I am creating a mobile game where if the player taps the screen, a ball drops from the top of the screen. The problem is with the UI. When I tap the pause, settings, or home buttons, it still counts it as tapping the screen and a ball drops. I want to make it so that when you press a button, it counts as tapping just the button and not both the screen and the button.
Found in this post: UI buttons and touch input problem - Questions & Answers - Unity Discussions
In your Update(), make your check for finger press like:
foreach (Touch touch in Input.touches)
{
if (touch.fingerId == 0)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
if (!IsPointerOverUIObject(Input.GetTouch(0)))
DoTheThing();
}
}
}
Then make a separate method IsPointerOverUIObject():
private bool IsPointerOverUIObject(Touch touch)
{
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(touch.position.x, touch.position.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}