Is there a lowest-level editor window/permanent editor window?

I want to create an editor extension that will execute code before Unity finally closes. It’s not intrusive, so don’t worry about me trying to stall anything :slight_smile: Anywho, I need this to execute no matter what window is opened, so I do not want the user to have to have a window present. It’d be nice if it worked on a window that is usually opened most all the time (like the Scene or Heirarchy), but even if the user has that window closed, it won’t execute, making it a problem.

So that leads me to my question: Is there a “lowest level” editor window, that by “closing” would close out the whole editor? This means that it would work perfectly for this case. Also, how would I get this to extend that editor window, if that was the case (even if it must be on the scene/heirarchy)?

Well, there’s only one top window type in Unity and that’s the internal “ContainerWindow”. It basically wraps the native window. Those ContainerWindows can hold a “View” (also an internal class). There are different built-in views:

  • MainWindow (derived from View)
  • HostView (derived from GUIView)
  • DockArea (derived from HostView)
  • SplitView (derived from View)

If you create an EditorWindow class, that actually sits inside a HostView which usually sits inside a DockArea which may sit inside a SplitView and finally inside a ContainerWindow.

However all those internal classes can’t be accessed any can’t be extended. Even if you could they don’t have any method / callback when they are “closed”. Well, they have as they are all ScriptableObjects and therefore they have an OnDestroy method, however that isn’t called when the editor is closed as the whole scripting engine just shuts down.

The only thing that is called when you close the editor is the destructor / finalizer of such a ScriptableObject. As you might know the finalizer is called from the GC thread so at that point you can’t use any API Unity offers and you should be careful what you do inside the finalizer because as long as you stay inside that thread, the GC is blocked. If you do something that requires a GC collect it will dead lock the GC and therefore your whole application.

In addition to those problems you should be aware of the fact that Unity actually restarts the whole managed environment whenever you enter playmode. At this point all classes will be destroyed and recreated from a serialized version. So it’s difficult to detect if you actually shutdown the editor or if you just entered playmode or if Unity just recompiled a script in which case it also restarts the environment.

So in short there’s no realiable way to detect a shutdown of the editor. What kind of code do you want to execute? As i said you can’t use any Unity API, neither the usual game API nor the editor specific stuff. So all you can do is plain old C# / Mono / .NET code.