在Unity的UI上注册触摸

本文关键字:注册 触摸 UI Unity | 更新日期: 2023-09-27 18:16:33

我需要忽略一些功能,如果我碰巧触摸到我的UI。然而,我很难察觉到我是否真的触摸到了它。

我的UI使用Unity内部的原生UI。我的想法是简单地检查图层,如果我触摸了图层上的任何东西,我就会阻止任何功能的发生。

所以我写了这个来测试它:

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

然而,当我按下UI上的按钮时(它由Canvas, Panel和单个按钮组成),什么也没有发生。但是,如果我在场景中放置一个立方体并将其分配给UI层,则会出现调试日志。

为什么?

在Unity的UI上注册触摸

我猜关键是:EventSystems.EventSystem.current.IsPointerOverGameObject()

无论你是悬停UI,它都应该返回true。试着像这样实现它:

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

对于2d元素,你需要使用Physics。Raycast2d而不是物理。并确保你的UI元素有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 );
        }