UGUI全局监控鼠标单击状态
程序员文章站
2022-06-08 18:33:27
...
本文地址:https://blog.csdn.net/t163361/article/details/108598588
项目想做一个类似菜单的功能,单击非菜单部分关闭菜单列表。查了一圈没有开放的全局点击接口可用,然后去翻UGUI的源码,在PointerInputModule中发现了事件字典m_PointerData。这个成员保存所有触发的鼠标事件。然后使用反射实现了此功能。
代码如下:
反射代码
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Utils.UnityEngineUtils.Proxy
{
public static class ProxyStandaloneInputModule
{
private static StandaloneInputModule inputModule;
private static FieldInfo m_PointerData;
public static Dictionary<int, PointerEventData> GetPointerData()
{
if(m_PointerData == null)
m_PointerData = typeof(StandaloneInputModule).GetField("m_PointerData", BindingFlags.Instance | BindingFlags.NonPublic);
if (inputModule == null)
inputModule = GameObject.FindObjectOfType<StandaloneInputModule>();
if (inputModule != null
&& m_PointerData != null)
{
return m_PointerData.GetValue(inputModule) as Dictionary<int, PointerEventData>;
}
return null;
}
}
}
部分实现代码
private RectTransform _rectTransform;//菜单父节点
Dictionary<int, bool> clickStates = new Dictionary<int, bool>();
private void CheckMenuHide()
{
var pointers = ProxyStandaloneInputModule.GetPointerData();
if (pointers != null)
{
bool click;
foreach (var pointerData in pointers)
{
if (clickStates.TryGetValue(pointerData.Key, out click))
{
if (click != pointerData.Value.eligibleForClick && !click)
{
var go = pointerData.Value.pointerEnter;
if(!ClickMenuGameObject(go))
HideMenu();
}
}
else
{
clickStates[pointerData.Key] = pointerData.Value.eligibleForClick;
}
}
}
}
private bool ClickMenuGameObject(GameObject go)
{
if (!go)
return false;
return go.transform.IsChildOf(_rectTransform);
}
private void HideMenu()
{
_guicadViewModel.Unselect();
}
思路就是鼠标放开后,去遍历pointerEnter所指向的对象是否隶属于菜单父节点,不是的话,就触发隐藏菜单的操作