Call a method of a class to destroy the object that is calling it

Hi!

From a Character class I’m calling a GameMode’s method that will destroy this Character class that is calling the method:



void ASCharacter::OnDied(AActor* InstigatorActor)
{
   ASGameModeBase* GameMode = GetWorld()->GetAuthGameMode();
   if (GameMode)
   {
      GameMode->OnActorKilled(this, InstigatorActor);
   }
}

The GameMode method is:

void ASGameModeBase::OnActorKilled(AActor* VictimActor, AActor* Killer)
{
   ASCharacter* Player = Cast(VictimActor);
   if (Player)
   {
      // Other code…
      Player->Destroy();
   }
}

Could there be any issues that might arise from calling a method that will destroy the class that is calling it?

Thanks!

Hey there @ViaCognita! For most actors, I don’t foresee too many issues as long as anything that would be called on this actor or any pointers directed at it are handled carefully. Anything that could be called after it’s death but before it’s garbage collected should have an isValid check to make sure it doesn’t run (or more accurately doesn’t attempt to run on an actor that’s being garbage collected).

However, with player characters, it’s often better not to outright destroy and garbage collect them, but to hide, reset, and recycle them due to how many systems usually target players.

1 Like