在合成和发送自定义事件之前,应了解 UI 工具包事件系统如何分配和发送操作系统事件。
事件系统使用事件池来避免重复分配事件对象。要合成和发送自定义事件,应按照相同的步骤分配和发送事件:
using
块中以确保其返回到事件池。element.SendEvent()
。If you want to send events that usually come from the operating system, such as keyboard events and some mouse events, use a UnityEngine.Event
to initialize the UI Toolkit event.
以下示例演示了如何合成和发送事件:
void SynthesizeAndSendKeyDownEvent(IPanel panel, KeyCode code,
char character = '\0', EventModifiers modifiers = EventModifiers.None)
{
// 创建 UnityEngine.Event 以保存初始化数据。
// 此外,此事件将转发给 IMGUIContainer.m_OnGUIHandler
var evt = new Event() {
type = EventType.KeyDownEvent,
keyCode = code,
character = character,
modifiers = modifiers
};
using (KeyDownEvent keyDownEvent = KeyDownEvent.GetPooled(evt))
{
panel.SendEvent(keyDownEvent);
}
}