【问题标题】:How to ignore certain types of UI elements or use MouseButtonDown for layer?如何忽略某些类型的 UI 元素或使用 MouseButtonDown 进行图层?
【发布时间】:2021-05-16 17:00:56
【问题描述】:

我所有的游戏都是由 UI 制作的。当我按下鼠标左键时,我调用了一些函数。但它也会对 UI 按钮的点击做出反应,所以我想检查我是否点击了 UI 元素,然后决定要做什么。我找到 EventSystem.IsPointerOverGameObject() 可以提供帮助,但是,正如我所说 - 我的所有游戏都是由 UI 元素组成的,所以,如果我使用它 - 我无法在场景中做任何事情。有没有办法指出它应该忽略哪些元素?以按钮为例。或者有没有办法只为特定层调用Input.GetMouseButton(0)

【问题讨论】:

标签: c# unity3d


【解决方案1】:

改编自https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.GraphicRaycaster.Raycast.html

把你的按钮和任何你不想调用你的函数的东西放在一个单独的层中

public LayerMask clickable;//exclude the button layers here

GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
EventSystem m_EventSystem;

void Awake(){
    m_Raycaster = GameObject.FindObjectOfType<GraphicRaycaster>();
    m_EventSystem = GameObject.FindObjectOfType<EventSystem>();
}

void Update(){
    if (Input.GetKey(KeyCode.Mouse0))
        {
            //Set up the new Pointer Event
            m_PointerEventData = new PointerEventData(m_EventSystem);
            //Set the Pointer Event Position to that of the mouse position
            m_PointerEventData.position = Input.mousePosition;

            //Create a list of Raycast Results
            List<RaycastResult> results = new List<RaycastResult>();

            //Raycast using the Graphics Raycaster and mouse click position
            m_Raycaster.Raycast(m_PointerEventData, results);

            foreach (RaycastResult result in results)
            {
                //is the layer of the gameObject hit included in clickable?
                if(clickable == (clickable | (1 << result.gameObject.layer))) {
                    doYourFunction();
                    break;
                }
            }
        }    
}

【讨论】:

    猜你喜欢
    • 2012-03-08
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多