I have a UObject that I’m using as a “Damage Component”.
UCLASS(Blueprintable, BlueprintType)
class MOS_API UMOSDamageComponent : public UObject
The damage components are instantiated and sent to our pawns to register in a list:
The pawn updates the damage components on tick and manages when they are deleted… or they’re supposed to.
void AMOSCharacter::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
bool ItemsNeedingUnregister = false;
for (int i = 0; i < RegisteredDamageComponents.Num(); i++)
{
//Check if this object isn't marked for deletion
if (RegisteredDamageComponents[i]->IsValidLowLevel())
{
if (RegisteredDamageComponents[i]->bNeedsUnRegister)
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red,
FString::Printf(TEXT("Component marked for un register")));
RegisteredDamageComponents[i]->OnUnRegister();
ItemsNeedingUnregister = true;
}
else
{
if (RegisteredDamageComponents[i]->bNeedsTick)
{
RegisteredDamageComponents[i]->DamageComponentTick(DeltaTime);
}
}
}
}
//Attempt 1
//if any components need unregistering, copy over to a new list (avoids crash)
//https://answers.unrealengine.com/questions/272651/tarray-remove-function-call-cause-editor-crash.html
if (ItemsNeedingUnregister)
{
TArray<UMOSDamageComponent*> NewComponentList;
for (int i = 0; i < RegisteredDamageComponents.Num(); i++)
{
if (RegisteredDamageComponents[i]->IsValidLowLevel())
{
if (!RegisteredDamageComponents[i]->bNeedsUnRegister)
{
NewComponentList.Add(RegisteredDamageComponents[i]);
}
else
{
RegisteredDamageComponents[i]->MarkPendingKill();
RegisteredDamageComponents[i] = nullptr;
}
}
}
RegisteredDamageComponents = NewComponentList;
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red,
FString::Printf(TEXT("Unregistering components. Component size is now %d"), RegisteredDamageComponents.Num()));
//GetWorld()->ForceGarbageCollection(true);
}
}
The problem is, when I’m stress testing this I see my memory usage slowly climb over time.
Am I doing something wrong in marking these for garbage collection?
Even when I force garbage collection, my memory never stabilizes. Nor do I get a performance hit for forcing garbage collection every frame.