2025-03-10 10:18:11 +08:00

94 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<RectTransform>(), 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;
}
/// <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)
{
foreach (var item in results)
{
Debug.Log(item.gameObject.name);
}
return results[0].gameObject;
}
return null;
}
List<RaycastResult> list = new List<RaycastResult>();
//场景中的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<IPointerClickHandler>(item.gameObject);
//var go1 = ExecuteEvents.GetEventHandler<IEventSystemHandler>(item.gameObject);
}
}
}
}
}