I’m trying to have a static TArray of UObjects in my AActor-based class. I create the UObjects and fill this array with them in the class constructor. However, because I can’t mark a static TArray as a UPROPERTY, the UObjects in the array get garbage collected.
What’s the correct way to have such a static TArray in my class?
For such thing i just made function that has declaration of all values inside, and then returns that array. I could not find any other way that would be also readable in blueprints.
And declaring array in blueprints then using values in c++ is messed up.
If by “static” you mean the “singleton-like” statics - then ones that only exists in singular instance in the application, then in UE it’s wrong approach to make them literally static TArray<>.
The proper approach whould be a defining a regular UPROPERTY() TArray<> on a class that presents in a “single” instance.
Usually it’s a GameMode or GameInstance. May be PlayerController depending on goals. Personally i’m throwing all the “kinda-constant values that have to be initialized in bp, while still be accessible from c++” in GameInstance, as it’s “guaranteed” to present for the whole app lifetime.
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);
}