Hello, I’ve got a few singleton type classes in Unreal but am faced with a problem.
Static variables seem to persist in the editor even after the play ends, which is resulting in some odd behaviors for me.
Here’s an example in my Pause Screen widget class.
// HudPause.h
static UHudPause* Self;
// HudPause.cpp
UHudPause* UHudPause::Self;
//Called from another class when UHudPause is created
void UHudPause::Init()
{
Self = this;
}
//globally it can be used like this
UHudPause::Self->RunFunction();
Because it stores itself as a static variable, the whole class persists in the editor.
How would I setup a proper singleton so it removes itself when the editor stops playing?
Or is there a function I can call to nullify the static var when the editor ends play? (OnDestroy and EndPlay don’t seem to work for this)
You can uncheck ‘Use Single Process’ in the advanced PIE settings, but this does mean your iteration time increases. PIE shares the same process as the Editor, and static vars will therefore carry over.
One way you can use, is by creating a SharedRef<yourclass> inside unreal module system in a plugin, set a Protected variable inside you module and in your implementation create 1 unique instance inside virtual void StartupModule() override;
anyway, I believe is trivial use singleton for HUD, using singleton perhaps is for hardware plugins or global game managers, but in that case you can use GameInstance which is a singleton based class