🟥 Unity获得当前鼠标悬浮处UI
/// <summary> /// 获得当前鼠标悬浮处UI /// </summary> public static Transform GetOverUI(this Transform trans) { Transform obj = null; EventSystem uiEventSystem = EventSystem.current; if (uiEventSystem != null) { PointerEventData uiPointerEventData = new PointerEventData(uiEventSystem); uiPointerEventData.position = Input.mousePosition; List<RaycastResult> uiRaycastResultCache = new List<RaycastResult>(); uiEventSystem.RaycastAll(uiPointerEventData, uiRaycastResultCache); if (uiRaycastResultCache.Count > 0) { obj = uiRaycastResultCache[0].gameObject.transform; } } return obj; }
使用方法:
Transform overUI = transform.GetOverUI();
🟧 Unity获得当前鼠标悬浮处物体
/// <summary> /// 获得MainCamera下,当前鼠标下的3D物体 /// </summary> public static Transform GetOverObj(this Transform trans, Camera cam = null) { Transform obj = null; cam = cam == null ? Camera.main : cam; Ray ray = cam.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, cam.farClipPlane)) { // 如果与物体发生碰撞,在Scene视图中绘制射线 Debug.DrawLine(ray.origin, hit.point, Color.green); obj = hit.transform; } return obj; }
使用方法:
Transform overObj = transform.GetOverObj();
- 若你不是用MainCamera看场景的,那就将你正在使用的摄像机传入就好了。