Registering Touch on UI in Unity

蹲街弑〆低调 提交于 2019-12-12 03:17:41

问题


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?


回答1:


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!");
    }
}



回答2:


For a 2d elements you need to use Physics.Raycast2d instead of Physics.Raycast and make sure that your UI element have a 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 );
        }


来源:https://stackoverflow.com/questions/32997075/registering-touch-on-ui-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!