How can I clean up a TArray so destroyed instances are no longer taking up space in it?

I have an obstacle spawner that needs to keep track of all of the fences it spawns so it can tell them to accelerate continually. To do this, I have a TArray property.

TArray<AFenceObstacle*> Fences;

My idea is that I want my fences to despawn (destroy themselves) when they have gone far enough off screen. What I want to know is if any index of my TArray that points to a now-destroyed FenceObstacle will automatically point to nullptr?

I did an experiment, and it turns out that no, the pointers are NOT automatically set to nullptr when the Fence destroys itself. But by setting the pointer to nullptr after telling the Fence to destroy itself, I was able to call

Fences.Remove(nullptr);

to successfully clean up the TArray.

1 Like

Mark your array as UPROPERTY then they will be nullified on destroy.