2015-10-07 115 views
0

如果碰巧碰到我的UI,我需要忽略一些功能。但是,我正在努力檢測我是否真的觸摸它。在Unity中的UI上註冊觸摸

我的用戶界面使用Unity內的本地用戶界面。我背後的想法是簡單地檢查圖層,如果我觸摸該層上的任何東西,我會停止任何功能發生。

所以我寫了這個測試吧:

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按鈕(它是由帆布,面板和一個按鈕來測試的),沒有任何反應。但是,如果我在場景中放置一個多維數據集並將其分配給UI層,則會顯示調試日誌。

這是爲什麼?

+0

HTTP一個2D元素://答案.unity3d.com/answers/885196/view.html – Fattie

+0

[如何讓玩法忽略Unity3D中的UI按鈕的點擊?](http://stackoverflow.com/questions/35529940/how-to-make-gameplay -ignore-clicks-on-ui-button-in-unity3d) – Fattie

回答

1

我想這裏的關鍵是: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!"); 
    } 
} 
1

對於你需要使用的,而不是Physics.Raycast 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); 
     } 
+0

現代Unity的詳細和繁瑣的答案... http://answers.unity3d.com/answers/885196/view.html – Fattie