簡體   English   中英

在Unity中注冊UI上的Touch

[英]Registering Touch on UI in Unity

如果碰巧碰到我的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層,則會顯示調試日志。

這是為什么?

我猜這里的關鍵是: 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而不是Physics.Raycast並確保您的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 );
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM