Bug in the code of the lesson

This is the code for the lesson:

void AKillEmAllGameMode::PawnKilled(APawn* PawnKilled) 
{
    Super::PawnKilled(PawnKilled);

    APlayerController* PlayerController = Cast<APlayerController>(PawnKilled->GetController());
    if (PlayerController != nullptr)
    {
        EndGame(false);
    }

    for (AShooterAIController* Controller : TActorRange<AShooterAIController>(GetWorld()))
    {
        if (!Controller->IsDead())
        {
            return;
        }
    }
    
    EndGame(true);
}

This is really dirty/risky code. If the player loses (PlayerController != nullptr), we don’t return early after calling EndGame, nor is there an else statement for the if, so the range loop for checking the AI is executed.

Most of the time this will be OK because if we get killed, there is likely at least one AI still alive, so the early return in the range loop will exit the function.
But if the player and the last AI kill each other, then EndGame is be called twice (*)

(*) actually, it is called 3 times:

  • twice for the dead player pawn
  • a third for the dead AI pawn
1 Like

Privacy & Terms