Static variables in the Game Manager

I have a game manager which is a singleton pattern, is it ok to use static variables within that, I ask because I have seen loads of warnings in other threads.

The static I plan to use is only used once at the second scene and never changed after that.

Sure. Static properties on singleton classes are fine. They get a bad rep because it’s common for them to be misused/abused, but in themselves there’s nothing wrong with it. I have a GlobalStateDirector DontDestroyOnLoad singleton which keeps track of some critical global data, like the last checkpoint ID and the ID of the current scene, which needs to be kept somewhere. There’s definitely some data that it makes sense to have as global static data.

Normally, if you have a singleton, it’s not useful to have a static variable in addition, as you can always access the singleton.

There are 2 main differences between a static and a singleton:

  • the singleton must go through the constructor, so you can ensure some good initialization
  • the singleton may not be initialized when you access it (depending on how you create it)

Most of the time, people say that statics are bad because they break about every architecture rule.
In practice, it’s true that they can mess things a lot.
But in the end, it’s like everything else, they can be messy and be out of control if there are too many of them, but that’s true for everything.

My advice is: write comments.
When you do something you’re not sure about, add comments to explain why you do that, what it does and how to use it.
In fact, always comment, even if you’re sure about what you’re doing.
That’s better than following any ‘standard’ architecture rule.

1 Like

That should not be too much of an issue.

The way I feel about static variables is that if you use them, you are either covering a weakness that you don’t otherwise know how to overcome, or you are taking a shortcut to save development time. Either case is acceptable, but may lead to technical debt later in your project. Technical debt basically means that tasks may take longer and be more complicated than necessary.

What’s the problem you’re trying to solve?

The main reason that warnings against using static variables are common is that they seem like a really attractive solution to newbie programmers in lots of cases where they’re just going to cause trouble later.

Unity is littered with static properties, used correctly they are very useful and can result in cleaner code.

My advice is bear in mind the warnings of possible pitfalls, but don’t let it put you off using static properties. If you never use them you probably won’t learn how and when they can be useful and when to use a different approach instead.