I’ve got a simple game, and when you die, it reloads the level file, the easiest way to reset everything the way it is when you start the level. The problem is that it seems that static variables don’t get reset when I load a new level. Am I doing something wrong, or is this always the intended behaviour of static variables? I suppose this is because static variables aren’t bound to any particular object?
So here’s the question. Is there an easy way to reset static variables? I figure my options right now are to either define the values of every static variable in a Start function so they get reset when I reload the level, or to rewrite my code so these variables are not static. I’m thinking the latter is the best option right now. Mostly I set variables to be static just to make it slightly easier for me to call from other scripts, so they’re not really essential. But I don’t want to go ahead with anything that big yet until I think it’s the right thing to do (which it probably is).
It is the intended behavior. If you want the values in question to be reset when a new level loads, you’ll have to account for that in one way or another. (Making the variables non-static and accessing them via another method, as you mentioned, would probably be a good choice.)
Instead of using static variables, why not use a singleton design for your major classes? That way you can still easily access the variables (ClassName.Instance.Variable instead of ClassName.Variable) - but you wont have to worry about resetting everything manually.
Singleton doesn’t help here. The problem is that BlobVanDam has a certain time when he wants his variables reset, but the class does not know about it. A singleton allows late and complex instantiation, but it still has no idea that it should reset itself when a new level loads.
Sorry, I should have been more specific. Using a singleton design with a Monobehavior that does not make use of [DontDestroyOnLoad] will reset every time there is a scene change. By setting it up like this:
static ClassName _instance;
public static ClassName Instance {
get {
if (_instance == null){
_instance = GameObject.Find("GameScriptsContainer").GetComponent<ClassName>();
}
return _instance;
}
}
Every time the scene reloads, the object stored in _instance will be destroyed, so the getter for Instance will “find” the new object (with the fresh setup).
It will reset itself when a new level loads like other nonstatic variables, no?
I don’t see a problem of re-initializing the static variables when needed. Just make one function for that. You can list all the static variables that you want to reset in this function. Also, there are variables you don’t want to reset, like scores, lives, etc and you want to access from different scripts. Static variables is a natural choice there.