Search Unity

Loosing references between VisualElements on DetachFromPanelEvent

Discussion in 'UI Toolkit' started by cecarlsen, Jul 24, 2019.

  1. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    864
    How can I store persistent references between VisualElements?

    I extend VisualElement in a number of classes and some of them need to refer to one another. Sometimes, for example when I detach and reinsert the panel window that the elements live inside (DetachFromPanelEvent), the elements loose references to one another. Perhaps UIElements are destroying and recreating all elements in the background, what do I know.

    In a MonoBehaviour I would use the [SerializeField] attribute, but how do I make sure references survive in a VisualElement?
     
  2. antoine-unity

    antoine-unity

    Unity Technologies

    Joined:
    Sep 10, 2015
    Posts:
    780
    Hello,

    VisualElement references are not serializable therefore using [SerializedField] won't work. You shouldn't loose references between VisualElements when detaching/reattaching a window (I am assuming here that you are talking about docking a window in the Unity Editor or making it floating) because this window isn't actually destroyed (simply re-parented which sends a pair of DetatchFrom/AttachToPanel events.

    To deal with when a recompilation or entering in playmode you will need to find a different another approach that relying on VisualElement objects as those definitely do not survive the C# domain reload. In this case EditorWindow.OnEnable() is the starting point when the whole UI needs to be created (just like the first time).
    I would recommend using [SerializedField] in your custom window with types that can be serialized and somehow associated with the VisualElements you are about to create.

    If you could explain a bit more broadly what you are trying to achieve I can provide some advice, in the mean time I hope this helps.
     
  3. cecarlsen

    cecarlsen

    Joined:
    Jun 30, 2006
    Posts:
    864