First of all, it that possible to create custom event and use it in Register/Unregister callback?
And second question, how to send event from child visual element to parent visual element?
What I am trying to create - some generic editor window that accepts content VisualElement as a content and add it to Window.rootVisualElement. I want my button located in VisualElement send some CloseEditorWindowEvent and add callback for this event to Window.rootVisualElement in order to intercept it and close actual editor window. I want to do this in order to encapsulate content from knowing anything about where its located.
Thanks in advance.
I was not able to route my custom message until this reflection magic added.
public class CloseWindowEvent : EventBase<CloseWindowEvent>
{
public CloseWindowEvent()
{
}
protected override void Init()
{
base.Init();
PropertyInfo propagation = typeof(EventBase).GetProperty("propagation", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
propagation.GetSetMethod(true).Invoke(this, new object[] { 1 | 2 | 4 });
}
}
Internal unity code checks for propagation flag(which is 0 by default) and do nothing in case of 0. Not sure how to set it without reflection, since property is internal. Maybe Unity guys can help with this.
1 Like
Also, another solution without reflection:
var closeWindowEvent = ChangeEvent<WhateverUniqueType>.GetPooled();
closeWindowEvent.target = item;
item.SendEvent(closeWindowEvent);
Ensure to replace WhateverUniqueType to something unique to your event type. Use ChangeEvent in callbacks.
2 Likes
The EventBase class has the tricklesDown and bubbles protected properties that are accessible proxies to the propatagion internal property.
But how to set them without reflection? None of that properties has setters, that is why I used reflection.
Oh you’re right, the setters were introduced in 2020.2. If you’re on 2020.1 you can install the com.unity.ui package, otherwise I guess you’re stuck with reflection.
1 Like
Ha, I am on 2019.4. Anyway, thanks for replies, thats make sense now.