I’m trying to run a little editor script exactly once, when Unity is launched. It looks something like this:
[InitializeOnLoad]
static class MyStartupCode {
/// constructor
static MyStartupCode() {
// my code
}
}
This does indeed run when the editor is first opened. However, it’s also run every time my code recompiles (I’m assuming some assemblies are being reloaded/the static class is being reinitialised).
I’ve seen someone mention using if (!EditorApplication.isPlayingOrWillChangePlaymode), but this only prevents the code from running when I enter/exit Play mode.
Can I prevent this code from being run every time my code compiles?
Yeah, I tried adding something like static bool hasRunOnce = false; to the class, and then setting it to “true” once the code runs. But it seems that the whole class is reinitialised when my code is recompiled… so it always reverts back to the default “false” value, and then my code runs again.
As far as I know, there is no callback for when the editor starts, and as you’ve already experienced, static variables will be deleted and recreated sooner or later (when the assembly reloads due to recompile or potentially enter play mode depending on your settings).
So, you could use UnityEditor.SessionState to check if you’ve already initialized. This will persist for the entire duration while the editor is open.
Thanks! Available since v5.6 and I didn’t know about this. Could’ve saved me some good hours here and there.
I feel this info should be more available (not sure how)