TExcelTAD
Home › Unreal Engine 5 with C++ › GameMode, GameState & PlayerState

GameMode, GameState & PlayerState

Unreal's gameplay framework splits "the game" into classes with fixed jobs, and the split is driven by networking: which machine needs to know what. Even in a single-player game, putting data in the right class makes it work in multiplayer later and keeps code easy to find.

Class Exists on Job Example data
AGameModeBase / AGameMode server only the rules: who may join, what spawns, when the match ends spawn rules, score limit, which pawn class players get
AGameStateBase / AGameState server + every client (replicated) the public state of the match time left, team scores, match phase
APlayerState server + every client the public state of one player name, score, kills, team
APlayerController server + the owning client one player's will: input, camera, UI menu state, aim mode
APawn / ACharacter server + clients that can see it the body in the world health, movement
AHUD and UMG widgets owning client only drawing the UI widget references
UGameInstance each machine, for the whole run of the program survives level changes settings, session info

The base/derived pairs: AGameModeBase and AGameStateBase are minimal. AGameMode and AGameState add a match state machine (WaitingToStart, InProgress, WaitingPostMatch…) suited to round-based multiplayer. Use the Base versions unless you want that machine. A GameMode and GameState must come from the same family.

Setting the GameMode

The GameMode for a level comes from World Settings → GameMode Override, or the project default in Project Settings → Maps & Modes. Its default classes (pawn, controller, HUD, states) are set in its constructor or in a Blueprint subclass:

cpp
// ArenaGameMode.cpp
#include "ArenaGameMode.h"
#include "ArenaGameState.h"
#include "ArenaPlayerController.h"
#include "ArenaPlayerState.h"

AArenaGameMode::AArenaGameMode()
{
    GameStateClass = AArenaGameState::StaticClass();
    PlayerStateClass = AArenaPlayerState::StaticClass();
    PlayerControllerClass = AArenaPlayerController::StaticClass();
    // DefaultPawnClass is usually set in a Blueprint subclass (BP_ArenaGameMode) to a BP character with a mesh
}

void AArenaGameMode::PostLogin(APlayerController* NewPlayer)
{
    Super::PostLogin(NewPlayer);       // a player joined; NewPlayer->PlayerState is valid now
    UE_LOG(LogTemp, Log, TEXT("%s joined"), *NewPlayer->PlayerState->GetPlayerName());
}

void AArenaGameMode::OnEnemyKilled(AController* Killer)
{
    if (AArenaPlayerState* PS = Killer ? Killer->GetPlayerState<AArenaPlayerState>() : nullptr)
    {
        PS->AddKill();                                    // replicated: every client's scoreboard updates
    }
    if (AArenaGameState* GS = GetGameState<AArenaGameState>())
    {
        GS->EnemiesRemaining--;                            // replicated match state
        if (GS->EnemiesRemaining <= 0) EndArena(true);
    }
}

Where does it go?

Question Class
"How many points does a kill give?" GameMode: it is a rule, and clients don't need to know it
"How much time is left?" GameState: everyone displays it
"How many kills does Ada have?" PlayerState: everyone's scoreboard shows it
"Is the inventory menu open?" PlayerController (or the UI): only that player cares
"Where is Ada and how hurt is she?" the Pawn
"Keep the player's chosen difficulty across levels" GameInstance (or a UGameInstanceSubsystem)

A frequent bug: a client reads GetWorld()->GetAuthGameMode() and gets nullptr. The GameMode doesn't exist on clients. Put what clients need into GameState.

Another: storing a player's score on the Pawn. When the pawn dies and respawns, it is a new actor and the score is gone. PlayerState survives respawns (and, in multiplayer, reconnects briefly).

A model: who exists where

This model builds the actor list for a listen server (the host plays too) with two remote clients, using the rules from the table, then prints what each machine has. It is a handy picture to keep in mind when a Cast or GetFirstPlayerController() returns null on a client.

cpp · try it yourself
#include <iostream>
#include <string>
#include <vector>

enum class Where { ServerOnly, Everyone, OwnerAndServer, OwnerOnly };

struct Actor { std::string Name; Where Rule; int Owner; };   // Owner: player index, -1 = none

int main() {
    const int players = 3;                       // player 0 is the host of the listen server
    std::vector<Actor> actors = {
        {"GameMode", Where::ServerOnly, -1},
        {"GameState", Where::Everyone, -1},
    };
    for (int p = 0; p < players; p++) {
        std::string n = std::to_string(p);
        actors.push_back({"PC" + n, Where::OwnerAndServer, p});
        actors.push_back({"PS" + n, Where::Everyone, p});
        actors.push_back({"Pawn" + n, Where::Everyone, p});
        actors.push_back({"HUD" + n, Where::OwnerOnly, p});
    }

    for (int machine = 0; machine < players; machine++) {
        bool isServer = machine == 0;
        std::cout << (isServer ? "host (server + player 0):" : "client " + std::to_string(machine) + ":");
        for (const auto& a : actors) {
            bool has = a.Rule == Where::Everyone
                    || (a.Rule == Where::ServerOnly && isServer)
                    || (a.Rule == Where::OwnerAndServer && (isServer || a.Owner == machine))
                    || (a.Rule == Where::OwnerOnly && a.Owner == machine);
            if (has) std::cout << " " << a.Name;
        }
        std::cout << "\n";
    }
}
host (server + player 0): GameMode GameState PC0 PS0 Pawn0 HUD0 PC1 PS1 Pawn1 PC2 PS2 Pawn2
client 1: GameState PS0 Pawn0 PC1 PS1 Pawn1 HUD1 PS2 Pawn2
client 2: GameState PS0 Pawn0 PS1 Pawn1 PC2 PS2 Pawn2 HUD2

Two simplifications: pawns only replicate to clients for which they are relevant (roughly, close enough), and the listen-server host is both the server and player 0, which is why it has every PlayerController. A dedicated server would have all the PCs and no HUDs at all.

Test yourself

A client calls GetWorld()->GetAuthGameMode() and gets null. Why?

  1. The GameMode was destroyed
  2. The GameMode only exists on the server
  3. It must be cast first
  4. The level has no GameMode override

Where should a player's kill count live so it survives respawns and shows on everyone's scoreboard?

  1. Pawn
  2. PlayerController
  3. PlayerState
  4. HUD

Which class survives a level change?

  1. GameMode
  2. GameState
  3. GameInstance
  4. PlayerState