有时候,需要处理 UI 在前,3D 物体在后,射线检测时,点击UI,会穿过UI让 3D物体也触发了。
有两种方式
- 一种是通过EventSystem的RaycastAll检测
- 一种是通过GraphicRaycaster的Raycast检测
public static bool IsPointerOverUIObject()
{
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
return results.Count > 0;
}
public static bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition)
{
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = screenPosition;
GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>();
List<RaycastResult> results = new List<RaycastResult>();
uiRaycaster.Raycast(eventDataCurrentPosition, results);
return results.Count > 0;
}