Object references in TArray/TMap/and co

I have a group of objects that are intended to last throughout the entire lifetime of the game. According to the garbage collection wiki page I would want to decorate its declaration with UPROPERTY(). What happens in the case of a TArray though? Would the following be sufficient:


UPROPERTY()
TArray<CustomActor *> objectArray;

Or is something else required? I assume that the TArray Add function acts as a copy constructor so I could just do TArray<CustomActor>, but I want to be able to pass around a pointer to the elements inside.

As an aside, if I need to return a TWeakObjectPtr in a function, can I just pass along the raw pointer and it’ll get resolved automatically or do I need to do something explicit?

TArrays marked as UPROPERTY of UObjects (or structs flagged USTRUCT with their own UPROPERTY inside) participate fully in garbage collection. TMaps, unfortunately, do not, and will require that you implement the AddReferencedObjects function for the class to collect up the object references.

It is not valid to have arrays (or just a single instance) of Object/Actor. In general Object/Actor will always be interacted with as pointers.

I’m not quite clear on what you mean here, but if you mean that you have a situation like so:



TWeakObjectPtr<UObject> MyFunction()
{
   UObject* Obj;
   return Obj;
}


Yes, that is legal.

So just to be explicit, if I have the above declaration:


UPROPERTY()
TArray<CustomActor *> objectArray;

The actors whose pointers I add to that array will not be garbage collected out from under me?

Yes and no.

The garbage collection system itself won’t pick them off, but that is always true because all Actors are referenced by the Level’s Actors array.

When you change levels the Actors will be explicitly Destroyed as part of the level load process and the references in your TArray will be set to null. There are some ways to transition Actors between levels if you are using seamless transitions (see GetSeamlessTravelActorList on GameMode), but that isn’t a commonly used mechanism.

The objects only need to survive the duration of the level, so that should be fine. Thanks for the help.