1

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.

1 Answer 1

3

Use this inside your static constructor:

if (!EditorApplication.isPlayingOrWillChangePlaymode) {
    //Do constructor stuff
}
Sign up to request clarification or add additional context in comments.

8 Comments

You can't do this because you can't really call Unity's API from another Thread. The static constructor is being called from another Thread so I expect the XXX is not allowed to be called from a MonoBehaviour constructor exception from the Editor.
I think that he's using a simple script with a pure class with the [InitializeOnLoad] attribute, which calls the static ClassName() constructor. In that case he can call the EditorApplication property from inside the constructor. The script ofc is not attached to any gameobject, the class doesn't inherit anything.
Exactly, being it an editor script there's only one thread involved, so this solves my problem perfectly. Thank you @Galandil.
Oh I see. Script is not attached to any GameObject and inherits from nothing. This is why it's good for OP to post code.+1
@ximera can you elaborate what you did to solve your problem?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.