Synthesize and send events
Learn how to synthesize and send events from an example.
Read time 2 minutesLast updated a month ago
Before you synthesize and send custom events, understand how the UI Toolkit event system allocates and sends operating system events.
UI Toolkit sends events to visual elements through the panel. If an event has no target, it's sent to the root element of the panel. To have a propagation path, an element must have a target, and the sender must set that target in advance. Some event types don't need a target. For example, keyboard events are sent to the focused element, and pointer events are sent to the element under the pointer.
The event system uses a pool of events to avoid allocating event objects repeatedly.
To synthesize and send your own events:
- Get an event object from the pool of events.
- Fill in the event properties.
- Enclose the event in a block to ensure it's returned to the event pool.
using - Pass the event to .
panel.visualTree.SendEvent()
You can send operating system events, such as keyboard and pointer events. To do so, use a to initialize the UI Toolkit event.
UnityEngine.EventThe following example demonstrates how to synthesize and send events:
void SynthesizeAndSendKeyDownEvent(IPanel panel, KeyCode code, char character = '\0', EventModifiers modifiers = EventModifiers.None){ // Create a UnityEngine.Event to hold initialization data. var evt = new Event() { type = EventType.KeyDownEvent, keyCode = code, character = character, modifiers = modifiers }; using (KeyDownEvent keyDownEvent = KeyDownEvent.GetPooled(evt)) { panel.visualTree.SendEvent(keyDownEvent); }}