Proper way to implement a UObject singleton?

I am trying to implement a UObject that provides a static Get() method like in the Rocket Module Manager:

static FModuleManager& Get();

Currently I’m planning to just research standard C++ singleton design patterns (such as the ones here), but I wondered whether there was something already in place for this? Sort of like how I have been using standard C++ pointers and references until I discovered TSharedPtr and TSharedRef.

Is there a proper “Epic” way to go about doing this? Thanks!

The one thing that is different concerning implementing the C++ singleton design pattern for UObjects is that UObject classes are garbage collected, so you must maintain a reference to the instance of the singleton, or it will be automatically garbage collected and deleted. Other than that, the code would be the same as for any other C++ class.

To avoid having your singleton object garbage collected, you can maintain a reference in a few different ways. You can store a pointer to it in a globally accessible place like GameMode or GameState. Alternatively you could call the AddToRoot() function on your singleton object after you create it, and this will add it to the root set (objects in the root set are never garbage collected). Note that the pointer to the singleton object inside your singleton UObject class definition must be a UProperty for the garbage collection system to know about it.

I get this compiler error saying that I must use NewObject instead of the new operator. For a singleton pattern, my instance is static and so I cannot declare it UPROPERTY … and according to documentation, pointers that are not UPROPERTY cannot be reliable in terms of their lifespan. In this case, adding that variable to root set still prevents it being garbage collected?

I had the same question a couple days ago and I found this: Global data access, looks very promising, I’ll be implementing this in the next couple of days.

Hope this helps :slight_smile:

The approach described in that article has little to do with an actual singleton class. It merely uses the game engine’s GameSingleton property and does not prevent creation of multiple instances, which is the point of a singleton class. Furthermore you’ll be stuck in a dead end if you try to add another singleton class to your game as you won’t be able to assign two “singletons” to the same property.

hmm you are right on that, have you found a way to achieve this already?