unity2d防止在raycast2d命中时点击ui按钮

时间:2017-04-20 09:55:06

标签: c# uibutton raycasting

我有一个带有collider2d的游戏对象,它被设计成可点击的,我还有一个UI按钮,当玩家移动时它将跟随相机,有时它们可​​能重叠,当它们重叠时,当用户点击重叠时区域,我确信用户想要点击对象(这是通过raycast2d命中),所以我应该阻止点击该按钮。

可点击游戏对象的光线投射植入脚本如下:

 private void checkTouch()
    {
        if (Input.touchCount > 0 || Input.GetMouseButtonDown(0))
        {
            Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
            RaycastHit2D hit = Physics2D.Raycast(rayPos, Vector2.zero, 0f);
            if (hit)
            {
                Debug.Log(hit.collider.gameObject + "is hit");
                IInputBehavior inputBehavior = hit.collider.gameObject.GetComponent<IInputBehavior>();
                //IInputVehavior was a self-desgined C# interface which has a `OnClick()` method.

                if (inputBehavior != null)
                {
                   //here we should prevent the UIButton to be clicked, but how? 

                    inputBehavior.OnClick();
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

好的,所以我在工作,所以我无法给你准确的代码,但我可以指出你正确的方向。当你最初制作画布时它应该已经生成了一个事件系统(作为某个场景中的游戏对象),你需要在游戏对象中引用它,当ui在它上面时你不想点击它。 在你的游戏对象中,它是这样的:

if(GetComponent<EventSystem>().IsPointerOverGameObject) {
    // The mouse is obscured by a UI element
} else {
    // The mouse is not over a UI element
}

https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html

相关问题