Course contentsShow
← Unreal Engine Game Development
Lesson 124 of 8802. The Gameplay FrameworkFree lesson

Loading Saved Game State Data

You will write logic to load serialized SaveGame files and restore the player's previous state upon game startup or level loading.

Loading Saved Game State Data

In this lesson, you will learn how to retrieve serialized save files from your hard drive and apply that data back into your game objects to restore a player's previous state.

The Loading Workflow

Loading is essentially the inverse of saving. While saving takes your current variables and turns them into a file on the disk, loading reads that file back, converts it into an object, and pushes those values into your active game classes (like your Character or GameState).

To perform this, you typically use the LoadGameFromSlot function. It requires the name of the slot you used when saving. Once you get the reference to the loaded SaveGame object, you simply "cast" it to your specific SaveGame class to access your stored variables.

Implementation Example

Imagine you have a USaveGame subclass called UMySaveData that stores a PlayerHealth float. To restore this when the game starts, you would write logic similar to this in your GameInstance or GameMode:

// 1. Attempt to load the file
UMySaveData* LoadedData = Cast<UMySaveData>(UGameplayStatics::LoadGameFromSlot("Slot1", 0));

// 2. If it exists, update the game
if (LoadedData)
{
    // Apply the saved health to the currently possessed pawn
    APlayerCharacter* MyCharacter = Cast<APlayerCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn());
    if (MyCharacter)
    {
        MyCharacter->Health = LoadedData->PlayerHealth;
    }
}

Critical Considerations

When loading data, it is vital to check if the LoadGameFromSlot function actually returns a valid object. If the player hasn't saved yet, the function will return nullptr. Attempting to read from a null pointer will cause a crash, so always wrap your logic in an if statement to ensure the file exists before you try to access its properties.

Furthermore, because GameInstance persists between levels, it is the ideal place to trigger this logic during Init() or BeginPlay(), ensuring that your character state is restored immediately after a level transition or a fresh launch of the application.

Key Takeaway: Loading is the process of retrieving serialized data from a specific slot, verifying its existence to prevent crashes, and mapping those values back to your active gameplay classes.