在 Unity 中注册 UI 上的触摸
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、面板和一个要测试的按钮组成)时,没有任何反应。但是,如果我在场景中放置一个立方体并将其分配给 UI 层,则会出现调试日志。
这是为什么?
我想这里的关键是:EventSystems.EventSystem.current.IsPointerOverGameObject()
无论您是否在悬停 UI,都应该 return 为真。尝试像这样实现它:
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 );
}
如果我碰巧碰到我的 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、面板和一个要测试的按钮组成)时,没有任何反应。但是,如果我在场景中放置一个立方体并将其分配给 UI 层,则会出现调试日志。
这是为什么?
我想这里的关键是:EventSystems.EventSystem.current.IsPointerOverGameObject()
无论您是否在悬停 UI,都应该 return 为真。尝试像这样实现它:
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 );
}