Thanks for the advice. I actually figured out another solution using “AddToRoot()” function. If you call “AddToRoot()” on a UObject, the object will get attached to a global root object and will never get garbage collected.
So I have a static TArray in my class definition:
static TArray<UMYObjectType*> MyStaticArray;
Then in my class constructor I have something like this:
if(MyStaticArray.IsEmpty())
{
auto obj1 = CreateDefaultSubObject<UMyObjectType>(TEXT("ObjName"));
obj1.AddToRoot();
MyStaticArray.Add(obj1);
auto obj2 = CreateDefaultSubObject<UMyObjectType>(TEXT("ObjName2"));
obj2.AddToRoot();
MyStaticArray.Add(obj2);
}
This seem to work for me.