Surious Attach/Detach calls when UIDocument is Destroyed

Unity 2020.3.0f , UIToolkit preview 14

If you register callbacks to AttachToPanel / DetachFromPanel in a VisualElement, you will receive several calls to those callbacks on destruction

        public MyVisualElement()
            : base()
        {
            RegisterCallback<AttachToPanelEvent>((_) => Debug.Log("attach"));
            RegisterCallback<DetachFromPanelEvent>((_) => Debug.Log("detach"));
        }

If you destroy the gameobject that the UIDocument is on you will get the following callbacks for each element:

  • Detach
  • Attach
  • Detach
  • Attach
  • Detach

This does not seem sensible, especially as hierarchy changes are expected to be expensive

6986078--824678--upload_2021-3-29_16-47-44.png

I’m able to repro the Detach/Attach when toggling between edit and play mode, as this is tied to OnEnable and OnDisable. However, when deleting a GameObject, I only get a single Detach as expected.

If you clear the console before deleting the GameObject and still get multiple calls to Detach and Attach per element, please file a bug for it.

FYI: I attempted to reproduce in isolation but could not. If I manage to understand what I’m seeing and that it is indeed a bug I will report the issue

1 Like