In this lesson, you will learn how to capture your current game state and persist it to your local hard drive so that players can resume their progress after closing the game.
Understanding the SaveGame Object
In Unreal Engine, "serializing" means converting the active variables in your game (like player health, current score, or inventory items) into a format that can be stored in a file. The primary tool for this is the USaveGame class.
Think of a SaveGame object as a "snapshot" container. It is a simple Blueprint or C++ class where you define the variables you want to remember. Once you populate this object with the current player stats, you use the engine’s serialization system to "write" that snapshot to a physical file on the disk.
The Workflow: Save and Load
To manage this process, we follow a two-step cycle:
- Saving: When you want to save, you create an instance of your
SaveGameclass, copy your current gameplay values into it, and callUGameplayStatics::SaveGameToSlot. This function handles the heavy lifting of turning your object into a byte-stream and saving it to the local file system. - Loading: To restore your progress, you call
UGameplayStatics::LoadGameFromSlot. If a file exists with that name, the engine reconstructs theSaveGameobject, allowing you to read the data back out and apply it to your characters or controllers.
Here is a simplified look at how you might trigger a save in your logic:
// 1. Create the container
UMySaveGame* SaveInstance = Cast<UMySaveGame>(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
// 2. Assign current stats
SaveInstance->PlayerScore = CurrentScore;
// 3. Write to disk
UGameplayStatics::SaveGameToSlot(SaveInstance, "Slot1", 0);
By keeping this data separate from your active gameplay objects, you ensure that even if the game process is terminated, the values remain safely stored in a binary file within your project's Saved/SaveGames folder.
Key Takeaway: Serialization acts as a bridge between volatile memory (RAM) and long-term storage (Disk), allowing you to package your game’s variables into a persistent file for later retrieval.