AGameModeBase

Learn about AGameModeBase events in Unreal Engine 5, including PostLogin and Logout, with code examples for C++.

AGameModeBase - Unreal Engine 5 Game Mode Events

The AGameModeBase class in Unreal Engine 5 is fundamental for defining the rules and core logic of a game. It handles game state, player spawning, and other essential game-related functionalities. This document details key events within AGameModeBase that are crucial for managing player connections and disconnections.

Event OnPostLogin

The PostLogin event is triggered in AGameModeBase every time a new player successfully logs into the game server. This is an ideal place to perform actions related to a newly connected player, such as assigning them to a team, granting initial items, or updating game state.

event_login

.h File Declaration:

public:
    // This method gets called every time a user logs in
    virtual void PostLogin(APlayerController* NewPlayer) override;

.cpp File Implementation Example:

void ExampleGameMode::PostLogin(APlayerController* NewPlayer)
{
    Super::PostLogin(NewPlayer);

    // Add custom logic here for when a player logs in.
    // For example, you might want to log the player's name or assign them a starting character.
    if (NewPlayer)
    {
        UE_LOG(LogTemp, Warning, TEXT("Player logged in: %s"), *NewPlayer->GetName());
    }
}

Event OnLogout

The Logout event is called in AGameModeBase whenever a player disconnects from the game server. This event is essential for cleaning up resources, updating player lists, and handling any game state changes that occur due to a player leaving.

event_logout

.h File Declaration:

public:
    // This method gets called every time a user logs out
    virtual void Logout(AController* Exiting) override;

.cpp File Implementation Example:

void ExampleGameMode::Logout(AController* Exiting)
{
    // Add custom logic here for when a player logs out.
    // For example, you might want to remove the player from a scoreboard or free up their slot.
    if (Exiting)
    {
        UE_LOG(LogTemp, Warning, TEXT("Player logged out: %s"), *Exiting->GetName());
    }
    Super::Logout(Exiting);
}

Further Reading