Implementing a Singleton pattern – understanding why it’s a Pandora’s box
The official point of the Singleton pattern is to ensure there is only one instance of a class in existence at any one time, hence the name “single”-ton. Unfortunately, this often gets packaged and confused with a public static variable to this one existing object. The actual idea of only having one object instance of a class makes sense. You might have a manager that needs to exist in every level, but if you don’t know the path the player took to get to this level, then you have no idea if one has been spawned yet. The solution is to make the manager a Singleton class and have a copy at every level. We can do this with the following code, using a static variable pointing to the one that exists:
Example Singleton.h excerpt
UCLASS() public Singleton : public AActor { static TObjectPtr<Singleton> _instance; public: ...