After restart game static variables are not resetting

Hello,
how is it possible that a static variable is not resetting after restart game?
I have several scenes and therefore I need static variables in the game manager, to keep some values.
About a week ago I already had several levels and it still worked there with the static variables and resetting them after restart game, but now all of a sudden it doesn’t anymore, although I haven’t changed anything in the game manager.
Where could this problem come from?

Maybe someone has an idea.
Thank you

This is one of the dangers of using static variables in general. The lifecycle of the variable is not clearly defined. In the editor, weird things may happen with static variables. They may keep data between runs if the editor does not tear down the C# runtime.

It’s best to use static variables only where they are really necessary. And in those cases, you must carefully manage them. Initialize them when they need to be initialized and reset them when they need to be reset.

Having several scenes does not necessitate the use of static variables at all. I think you should revisit that assumption. Limit your static variables only to where they are strictly necessary.

4 Likes

Try saying

void Start() {
YourStaticVar = valueYouWant;
}

But isn’t it changing the value in every scene? because start is called in every scene, right?

“Start is only ever called once for a given script”

I would recommend memorizing this. :slight_smile:

https://docs.unity3d.com/Manual/ExecutionOrder.html

1 Like

[quote=“Zeppi123, post:1, topic: 884957, username:Zeppi123”]
Where could this problem come from?
**[/quote]
**
Go to Project Settings / Editor and uncheck Enter Play Mode Settings

5 Likes

You seriously should fix your post … start() is going to get you nowhere. Start() might.

1 Like

Oh no lol

1 Like

They will always reset at runtime (if you restart the actual game) and using static variables is not a danger at all, but the editor has some optimization settings to enter the play mode faster.

This should be disabled by default (static variables should reset by default), maybe you changed the setting without realizing the side effect or miss clicked:

2 Likes

Thank you man, I was going a bit crazy not knowing why my static vars were not resetting

1 Like