Implementing (respawn) delay in C++

So I have this method inside my GameState class that handles respawning a player by telling its authority game mode to restart that player:

void AGameStateMatch::RespawnPlayer(AShootGunCharacter* PlayerToRespawn) {
  // Store a reference to our character's controller
  AShootGunPlayerController* PlayerController = Cast<AShootGunPlayerController>(PlayerToRespawn->GetController());

  // Destroy the player actor
  PlayerToRespawn->Destroy();

  // Tell the server to restart our player
  AGameplayGameMode* GameMode = Cast<AGameplayGameMode>(AuthorityGameMode);
  if (GameMode != nullptr) {
    GameMode->RestartPlayer(PlayerController);
  }
}

What I want to do is add an X second delay prior to the call to RestartPlayer() so that the player isn’t immediately respawned. I read some forum posts regarding using FTimerHandle and GetWorldTimerManager().SetTimer() but when I do this, it crashes:

FTimerHandle TimerHandle;
GetWorldTimerManager().SetTimer(TimerHandle, [&]() {
    GameMode->RestartPlayer(PlayerController);
}, 5, false);

Solved. Solution was to create a new function in my GameState class that’s a UFunction and handle the restart logic there. Then use a FTimerDelegate to bind that function by name and call SetTimer() with that delegate:

/// UFUNCTION() void PlayerRestartDelayed(AShootGunPlayerController* PlayerController)

void AGameStateMatch::PlayerRestartDelayed(AShootGunPlayerController* PlayerController) {
  AGameplayGameMode* GameMode = Cast<AGameplayGameMode>(AuthorityGameMode);
  if (GameMode != nullptr) {
    GameMode->RestartPlayer(PlayerController);
  }
}

/// RespawnPlayer()
void AGameStateMatch::RespawnPlayer(AShootGunCharacter* PlayerToRespawn) {
  // ... previous code

  // Tell the server to restart our player
  FTimerHandle TimerHandle;
  FTimerDelegate TimerDelegate;
  TimerDelegate.BindUFunction(this, "PlayerRestartDelayed", PlayerController);

  GetWorldTimerManager().SetTimer(TimerHandle, TimerDelegate, 5.f, false);
}
1 Like