using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; /******************************************************************************* *Create By CG *Function *******************************************************************************/ namespace Test { public class Test2 : MonoBehaviour { public GameObject uiElement; void Update() { //if (IsMouseOverUI(uiElement)) //{ // Debug.Log("鼠标在UI上"); //} //if(RectTransformUtility.RectangleContainsScreenPoint(uiElement.GetComponent(), Input.mousePosition, Camera.main)) // { // Debug.Log("鼠标在UI上"); // } //ClickUI(); GetOverUI(GameObject.Find("Canvas")); } private bool IsMouseOverUI(GameObject uiElement) { PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.mousePosition; if (EventSystem.current.IsPointerOverGameObject()) { return true; } return false; } /// /// 获取鼠标停留处UI /// /// /// public GameObject GetOverUI(GameObject canvas) { PointerEventData pointerEventData = new PointerEventData(EventSystem.current); pointerEventData.position = Input.mousePosition; GraphicRaycaster gr = canvas.GetComponent(); List results = new List(); gr.Raycast(pointerEventData, results); if (results.Count != 0) { foreach (var item in results) { Debug.Log(item.gameObject.name); } return results[0].gameObject; } return null; } List list = new List(); //场景中的EventSystem private void ClickUI() { //鼠标位置 PointerEventData eventData = new PointerEventData(EventSystem.current); eventData.position = Input.mousePosition; EventSystem.current.RaycastAll(eventData, list); foreach (var item in list) { if (item.gameObject != null) { Debug.Log(item.gameObject.name); //获取父类中事件注册接口 //当然可以细分为IPointerClickHandler, IBeginDragHandler之类细节一点的,各位可以自己取尝试 //var go = ExecuteEvents.GetEventHandler(item.gameObject); //var go1 = ExecuteEvents.GetEventHandler(item.gameObject); } } } } }