Singleton pattern in c++

I ran into a similar problem in the past. ONE solution is not to use singletons (i.e. try to force general programming patterns into an engine with its own framework and workflow). The way to cleanly integrate single-instance objects into Unreal is to put them either into the GameMode or GameInstance. The former is per-level, while the latter carries over. You have to decide which one is better for your particular use case.

For example: My SaveGameManager is instantiated by the GameInstance, since I can’t have it reset whenever the player switches levels. This means that it’s created before the first level is loaded and destroyed just before the game quits. I have a class that manages footstep sound mappings (surface to a set of sounds). Since all characters use the same mappings, I only need one instance of it. That one goes into the GameMode and is thus created at the beginning of a level and destroyed once it’s left. And for the intended purpose, that’s perfectly alright, because that object doesn’t need to carry over data across level transitions.

I faced the same situation in Unity and it has been the same thing: Using the framework as intended (in your case: designing your systems around the lifecycle the engine expects objects to have) unfailingly was less work than trying to force the engine to play nice with a system that wasn’t designed with the engine’s framework in mind. I had to deal with cascading workarounds, because something always broke somewhere. Then I redesigned it around how Unity expects GameObjects to work and guess what? It just worked.

So my recommendation to you would be to reassess the problem at hand. Study the UObject/AActor life-cycles and the gameplay framework. As big as the latter is, chances are Epic has already put something into place where your system would integrate beautifully and headache-free.

8 Likes