Registering user interface touches in Unity

I need some funcitonality to be ignored if I touch my user interface. However, I am struggling to determine if I really touch this or not.

My user interface uses its own user interface inside Unity. My thought was to just check the layers, and if I touched anything on that layer, I would stop any functionality.

So I wrote this to check it out:

    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 click a button on my user interface (it consists of a canvas, a panel, and one button for verification), nothing happens. However, if I put the cube in the scene and assigned it to the user interface level, a debug log will appear.

Why?

0
2

, : EventSystems.EventSystem.current.IsPointerOverGameObject()

true, . :

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

2d Physical.Raycast2d Physical.Raycast , Collider2D

RaycastHit2D hit = Physics2D.Raycast(worldPoint,Vector2.zero);

        //If something was hit, the RaycastHit2D.collider will not be null.
        if ( hit.collider != null )
        {
            Debug.Log( hit.collider.name );
        }
+1

Source: https://habr.com/ru/post/1628642/


All Articles