一篇文章搞懂unity编辑器中Event的rawType, type和GetTypeForControl
简介
Event.rawType
就是初始的type,可以通过Event.Use()
将rawType修改为EventType.Used
。
Event.type
是经过GUIClip过滤的rawType,如果事件触发时,鼠标位置位于当前GUIClip中,返回rawType,如果鼠标不在当前GUIClip中,则设置为EventType.Ignore
Event.GetTypeForControl
相对于Event.type
在GUIClip过滤的基础上,增加了hotControl的判断,如果是hotControl,也直接返回rawType。
验证代码
鼠标点击浅色区域,此时鼠标位置位于GUIClip区域之外,GUICLip内的代码调用rawType会是MouseDown
,type
会是Ignore
,由于设置了hotControl,GetTypeForControl
会是MouseDown
。
在我们重置hotControl为0时,GetTypeForControl
的值也变成Ignore
.
鼠标点击深色区域,此时鼠标位置位于GUIClip之内,此时 rawType, type 以及 GetTypeForControl 的结果都是MouseDown
public class EventDemoEditorWindow : EditorWindow
{
[MenuItem("Demos/EventDemoEditorWindow")]
static void ShowWindow()
{
var window = GetWindow<EventDemoEditorWindow>();
window.titleContent = new GUIContent("EventDemoEditorWindow");
window.Show();
}
private Event eventCache;
private int buttonControlId;
private void OnEnable()
{
}
private void OnGUI()
{
//Event.GetTypeForControl
eventCache = Event.current;
if (MGUILayout.Button($"按钮1"))
{
Debug.Log("点击 按钮1");
}
var buttonRect = GUILayoutUtility.GetLastRect();
buttonControlId = GetLastControlId();
GUIUtility.hotControl = buttonControlId;
//GUIUtility.hotControl = 0;
//鼠标需要点击 ClipRect 的上方区域
var clipRect = Rect.MinMaxRect(0, buttonRect.yMax+100, position.width, position.height);
//if(eventCache.type == EventType.Repaint)
GUI.Box(clipRect, string.Empty);
//buttonControlId = GetLastControlId();
//GUIUtility.hotControl = buttonControlId;
GUI.BeginClip(clipRect, default(Vector2), default(Vector2), false);
{
if (eventCache.rawType == EventType.MouseDown)
{
EventType type;
type = eventCache.rawType;
Debug.Log($"rawType = {type}");
type = eventCache.GetTypeForControl(buttonControlId);
Debug.Log($"GetTypeForControl={type}");
type = eventCache.type;
Debug.Log($"type={type}");
GUIUtility.hotControl = 0;
Debug.Log("---------------- Set HotControl=0 ----------------- ");
type = eventCache.rawType;
Debug.Log($"rawType = {type}");
type = eventCache.GetTypeForControl(buttonControlId);
Debug.Log($"GetTypeForControl={type}");
type = eventCache.type;
Debug.Log($"type={type}");
eventCache.Use();
Debug.Log("------------------ Event.Use() ------------------- ");
type = eventCache.rawType;
Debug.Log($"rawType = {type}");
type = eventCache.type;
Debug.Log($"type={type}");
}
}
GUI.EndClip();
GUIUtility.hotControl = 0;
}
private int GetLastControlId()
{
var type = typeof(EditorGUIUtility);
var field = type.GetField("s_LastControlID", BindingFlags.Static | BindingFlags.NonPublic);
var lastControlID = (int)field.GetValue(null);
return lastControlID;
}
}
分类:
Unity / Editor
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)