Unity解决点击UI穿透触发collider OnMouse事件的问题

前言

遇到了点击UI同时触发UI下面collider的OnMouse事件的问题。

解决方法

1.以前看过一点UGUI的源码,其实无论是UI点击检测还是OnMouse事件都是通过射线检测触发的。
我们可以通过在OnMouse事件里加上!EventSystem.current.IsPointerOverGameObject()判断。如果collider上面点到了UI EventSystem.current.IsPointerOverGameObject()就会返回true,所以这里要取反。
2.但是我遇到的情况有点特殊,因为游戏物体上面始终有一个提供拖拽功能的UI,这个UI是要用到点击检测的所以不能取消Raycast选项,所以我需要过滤掉这个需要用到的UI。我的方法是使用EventSystem.current.currentSelectedGameObject获取到点击对象针对性进行过滤。
类似功能的还有EventSystem.current.firstSelectedGameObjectEventSystem.current.lastSelectedGameObject

猜你喜欢

转载自blog.csdn.net/qq_39162826/article/details/121463471