Search code examples
c#unity-game-enginetouchunity3d-gui

Registering Touch on UI in Unity


I'm needing to have some funcitonality ignored, if I have happen to touch my UI. However, I am struggling to detect if I am actually touching it or not.

My UI makes use of the native UI inside Unity. My thought behind it was to simply check the layers and if I touched anything on that layer, I'd stop any functionality from happening.

So I wrote this to test it:

    void Update () {
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
    {
        Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
        RaycastHit hit;

        if ( Physics.Raycast(ray, out hit,  Mathf.Infinity, mask))
        {
            Debug.Log("hit ui");
        }
    }
}

However, when I press the button on my UI (it's comprised of a Canvas, Panel and a single button to test), nothing happens. However, if I place a cube in the scene and assign that to the UI layer, the debug log appears.

Why is that?


Solution

  • I guess the key here is: EventSystems.EventSystem.current.IsPointerOverGameObject()

    It should return true whether you are hovering UI. Try implementing it like this:

    using UnityEngine.EventSystems;
    ...
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
    {
        if(EventSystems.EventSystem.current.IsPointerOverGameObject()) {
              Debug.Log("UI hit!");
        }
    }