根据UGUI的射线检测机制获取当前鼠标下的UI:
/// <summary> /// 获取鼠标停留处UI /// </summary> /// <param name="canvas"></param> /// <returns></returns> public GameObject GetOverUI(GameObject canvas) { PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.mousePosition; GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>(); List<RaycastResult> results = new List<RaycastResult>(); gr.Raycast(pointerEventData, results); if (results.Count != 0) { return results[0].gameObject; } return null; }
其中,results为鼠标下UI的列表。
不仅适用于UGUI,可以在摄像机上添加PhysicsRaycaster组件,传参为摄像机,这样就可以获取3D物体。
/// <summary> /// 获取鼠标停留处物体 /// </summary> /// <param name="raycaster"></param> /// <returns></returns> public GameObject GetOverGameObject(GameObject raycaster) { PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.mousePosition; PhysicsRaycaster pr = raycaster.GetComponent<PhysicsRaycaster>(); List<RaycastResult> results = new List<RaycastResult>(); pr.Raycast(pointerEventData, results); if (results.Count != 0) { return results[0].gameObject; } return null; }