Static Constructor of Class with InitializeOnLoad Attribute

Hi, I wrote a class with InitalizeOnLoad attribute to do some work when I press the play button to start playing a scene. But I found that everty time I changed any script, the static constuctor of the class is called, and I don’t know how to check whether the game is running or not inside the constructor.

I have checked some fields of EditorApplication, like isPlaying, isPlayingOrWillChangePlaymode, isPaused, isCompiling, timeSinceStartup, …etc., but didn’t find anything useful.

Please help me.
Thanks in advance.

What, so Application.isPlaying dosn't work for you?

I tried only EditorApplication.isPlaying, and it was false inside the constructor called both when after compiling and after pressing the play button. I will try Application.isPlaying tomorrow. Thanks.

Hi, I tried Application.isPlaying. It also has false value in both conditions.

I recommend rethinking your architecture, then. One of the disadvantages of using a system like Unity is the limitations on what you can normally do in your code.

Thanks for recommendation. In fact, this problem is not so critical. It seems that the two conditions where the static constructor is called use different memory spaces. I just want to find a way to avoid potential errors.

1 Answer

1

The InitializeOnLoad attribute is for editor scripts. I looked over the documentation, and I’m not sure it has any effect in play mode.

To get code to execute first, you can put it inside a component and set a custom execution order so that component runs before anything else. That also lets the code run in the thread it’s meant to run in, and you will avoid errors when accessing standard Unity functions (like Application.isPlaying or Debug.Log).