EditorWindow Maximize/Unmaximize

Unity does a weird thing with docked windows when using Maximize, then Unmaximize (uncheck Maximize). When a docked window is maximized, either through the context menu or the space bar, Unity calls OnFocus and OnLostFocus a few times in a row ending with the window focused. When the window is restored, a new instance of the window gets created but never actually becomes visible.

Using Debug logs, what I’m seeing is this sequence

  1. OnEnable on new window
  2. OnFocus on new window
  3. OnLostFocus on old window
  4. OnLostFocus on new window
  5. OnFocus on old window
  6. OnFocus on old window again
  7. OnDisable on new window
  8. OnDestroy on new window
  9. OnFocus on old window

As far as I can tell, the UnityEditor.WindowLayout.Unmaximize() function is the culprit. It’s loading some kind of serialized copy of the window stored as an editor layout. I guess it was created when the window was maximized in order to preserve the window’s dimensions and docked position. Then, when it restores from the layout, it has to deserialize it from the layout file which essentially makes a new instance. It then has to destroy that new instance.

You might be asking, so what? Well, if you have a window that tries to preserve its data by using ScriptableObjects for when the window gets closed and reopened, it matters. Because when the new window instance is created in the background it “steals” the data references and then silently kills them by orphaning those references. So, the old window, the one you are left with has a bunch of dead ScriptableObject references that don’t actually point to your data.

I ran into this with JumpTo. Gonna have to refactor a good bit to work around it.