Example code for Unity using C# to detect mouse button down event

The values assigned to buttons are as follows: 0 for the primary button (usually the left button), 1 for the secondary button, and 2 for the middle button. Unlike other programming languages, C# does not rely on code blocks that are indented.


Solution:

To label your UI button, simply use a tag such as

"UI"

.

This function determines if a UI tag was present on the UI object clicked. This lets you verify in your screen tap function if the event should be triggered or not.

public static class InputHandler
{
    public const string CompareTagForUIElements = "UI";
    public static bool IsPointerOverUIObject(int touchId)
    {
        var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        // I'm using touch since you are talking about smartphones, 
        // if you still need click use Input.mousePosition
        eventDataCurrentPosition.position = new Vector2(GetTouch(touchId).position.x, GetTouch(touchId).position.y);
        List results = new List();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
        for (int i = 0; i < results.Count; i++)
        {
            if (results[i].gameObject.CompareTag(CompareTagForUIElements))
                return true;
        }
        return false;
    }
}

So rather than

public void ITappedOnScreen()
{
    if(Input.GetMouseButtonDown(0))
        Debug.Log("Screen tapped");
}

use

public void ITappedOnScreen()
{
    if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Begin &&
        !InputHandler.IsPointerOverUIObject(0))
        Debug.Log("Screen tapped");
}

Frequently Asked Questions

Posted in Uncategorized