Singleton, static, how to avoid?

I’ve started to read more about singleton pattern, and almost every source tells you should avoid both singleton and static classes, when it is possible, especially if it’s just replacement for global variables. And that’s exactly what it is used for in this course, so my question is, is it possible to avoid it? Is it good to use playerprefs to avoid the use of singleton? Or it is justified to use singleton to save data between scenes?

There are some good reasons for using singletons and static classes. Singletons have the disadvantage of dependencies and can lead to a lot of trouble when you rely to much on singletons, especially in bigger projects. Another possible way to go would be an event management system and use events.

Thx for your answer, what do you think is best way to handle game-related variables between scenes? I want to implement shop-like scenes in-between levels.

There a different ways you could go. You could use a singleton which doesn’t get destroyed on load. Or you save those information in a file before leaving a scene and load them in the new scene. It really depends on the scope of your project and internal system which way would be best for you.

If those informations are only needed between two scenes or they are not needed for a long term purpose… the use of a singleton could be justified. But if those informations are needed in a long term, p.ex. over different play sessions, some kind of a save file would be better.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms