Search code examples
c#unity-game-engineunity-editor

How to run a script only on Unity editor startup?


I'm writing my own autosave script for Unity editor and I want it to run its setup method when the editor is launched. I've tried using InitializeOnLoad, but it calls the static constructor not only when the editor starts but also every time the Play button is pressed, initializing again my script and resetting all its timers.

I've tried to put a condition to initialize the script only if the timers have their value set to the default value, but apparently InitializeOnLoad creates another instance of my script, so everything gets reset and the condition is useless.

Then I thought about creating a bool in the editor preferences at startup to check, when I press Play, if the script has been launched before. But then I can't find a way to reset this value when the editor is closed, so when I launch the editor again the bool is still true and the autosave doesn't start.

I also tried using ExecuteInEditMode to call the OnDestroy method and set the editor pref to false, but of course it only works when there's an instance of the script attached to a GameObject in the scene, which is not the case for an editor script.

Is there a solution to this out there? Thanks in advance.


Solution

  • Use this inside your static constructor:

    if (!EditorApplication.isPlayingOrWillChangePlaymode) {
        //Do constructor stuff
    }