简体   繁体   English

在Unity中注册UI上的Touch

[英]Registering Touch on UI in Unity

I'm needing to have some funcitonality ignored, if I have happen to touch my UI. 如果碰巧碰到我的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. 我的UI使用Unity内部的本机UI。 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. 但是,当我按下UI上的按钮(它由Canvas,Panel和一个要测试的按钮组成)时,什么也没有发生。 However, if I place a cube in the scene and assign that to the UI layer, the debug log appears. 但是,如果我在场景中放置一个多维数据集并将其分配给UI层,则会显示调试日志。

Why is that? 这是为什么?

I guess the key here is: EventSystems.EventSystem.current.IsPointerOverGameObject() 我猜这里的关键是: EventSystems.EventSystem.current.IsPointerOverGameObject()

It should return true whether you are hovering UI. 无论您是否悬停UI,它都应返回true。 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!");
    }
}

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