Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Event call when a VisualElement is removed

Discussion in 'UIElements' started by cecarlsen, Jun 26, 2019.

  1. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    514
    I am extending VisualElement and need to know when the element is removed from the hierarchy, so that I can automatically remove associated objects. But how?
     
    AndrewKaninchen likes this.
  2. SudoCat

    SudoCat

    Joined:
    Feb 19, 2013
    Posts:
    17
    By the looks of it, DetachFromPanelEvent should do what you want. It's fired when you remove an element from the hierarchy.
     
    cecarlsen likes this.
  3. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    169
    Yep, that's the way to do it.
     
    cecarlsen likes this.
  4. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    514
    Amazing, it works.

    If it was named OnDestroyEvent or OnRemoveEvent I would probably have found it.
     
    Last edited: Jun 28, 2019
  5. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    514
    Thanks @uDamian

    It seems that the event is not only fired when an element being deleted, but also when the panel window it lives inside is being detached and and reinserted in the Unity Editor, in which case the element is not actually removed. Perhaps it is being deleted and then recreated in the background, who knows.

    I need to know when the element is being removed for good. Is there any way to check for that?
     
  6. antoine-unity

    antoine-unity

    Unity Technologies

    Joined:
    Sep 10, 2015
    Posts:
    89
    Somewhat related to the other thread, there is no way to distinguish between those scenarios unfortunately.

    What kind of clean-up do you actually want to perform ? There might be several options like using a finalizer, using the dispose pattern or relying on the EditorWindow.OnDestroy() callback to deal with the whole window being removed.
     
    cecarlsen likes this.
  7. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    514
    Thanks @antoine-unity this was helpful.

    The specific case is a ConnectionElement that needs to call DetatchFromPorts on it's two related PortElements that removes references to it, but only when it is destroyed, not when the window is docked.

    I ended up calling target.RemoveFromHierarchy() when receiving the DetachFromPanelEvent in an ConnectionElement to make sure that the behavior is consistent when the event is fired (so that it will always mean the element is removed). Then I just check for change and regenerate the connections in window OnFocus.
     
    Last edited: Jul 25, 2019