Unity 获取鼠标悬停位置下的UI或3D物体对象
根据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; }
好好把握每一次学习的机会,你会发现自己时刻在成长!
不想放弃梦想,所以一直坚持,虽无人鼓励,但要活出自己!