第一种:
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("点击到UI");
}
第二种:
void Update()
{
if (IsPointerOverGameObject(Input.mousePosition))
{
Debug.Log("点击到UI");
}
}
private bool IsPointerOverGameObject(Vector2 mousePosition)
{
//创建一个点击事件
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = mousePosition;
List<RaycastResult> raycastResults = new List<RaycastResult>();
//向点击位置发射一条射线,检测是否点击UI
EventSystem.current.RaycastAll(eventData, raycastResults);
if (raycastResults.Count > 0)
{
return true;
}
else
{
return false;
}
}
上面两种方法鼠标进入带有collider的3d物体后也会判定为在ui上所以改为第三种
第三种:
private GraphicRaycaster graphicRaycaster;
private EventSystem eventSystem;
private PointerEventData eventData;
private bool init = false;
void Updata
{
Debu.Log(IsOnUIElement());
}
void Init()
{
if (!init)
{
graphicRaycaster = GameObject.Find("UI").GetComponent<GraphicRaycaster>();
// ↑这里要根据你自己的项目自己找canvas上的GraphicRaycaster
eventSystem = EventSystem.current;
eventData = new PointerEventData(eventSystem);
init = true;
}
}
/// <summary>
/// 是否在UI上
/// </summary>
/// <returns></returns>
public bool IsOnUIElement()
{
Init();
if (graphicRaycaster == null)
{
Debug.Log("无GraphicRaycaster,有问题");
return false;
}
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> list = new List<RaycastResult>();
graphicRaycaster.Raycast(eventData, list);
foreach (var temp in list)
{
if (temp.gameObject.layer.Equals(5)) return true;
}
return false;
}
原文链接:https://blog.csdn.net/qq_33994566/article/details/106069521