In this lesson, you will learn how to use the GameInstance class to store data that persists even after the level changes or a match ends.
Why do we need the GameInstance?
Up until now, we have worked with classes like Character and PlayerController. These are excellent for handling movement and input, but they share a major limitation: they are destroyed and recreated whenever you switch levels. If a player collects a specific item or earns a score in Level 1, that data disappears the moment you load Level 2.
The GameInstance is the solution to this problem. It is a special class that is created when the game starts and is only destroyed when the entire application closes. Because it sits "above" the level transition, it acts as the perfect "backpack" to carry data from one map to another.
Implementing Custom Data
To use this, you create a Blueprint (or C++ class) that inherits from GameInstance. Inside, you add variables like PlayerScore or InventoryItems.
For example, imagine your BP_MyGameInstance has an integer variable called TotalGold. When the player finishes a level, you can "set" this variable:
// Logic inside your PlayerController or Level Blueprint:
UGameInstance* MyGI = GetGameInstance();
UMyGameInstance* CastGI = Cast<UMyGameInstance>(MyGI);
if (CastGI)
{
CastGI->TotalGold += CurrentLevelGold;
}
When you call OpenLevel to travel to the next map, the PlayerController is destroyed, but your GameInstance remains active. Once the new level loads, you can simply access that same GameInstance and "get" your TotalGold to display it on the new level’s UI.
Setting Up
To make this work, you must tell Unreal Engine to actually use your custom class. Go to Project Settings > Maps & Modes and look for the Game Instance section. In the dropdown menu, select your custom class. If you don't do this, Unreal will continue to use the default empty GameInstance class instead of yours.
Key Takeaway: The GameInstance is a global, persistent container that stays alive throughout the entire application lifecycle, making it the perfect home for player progress, settings, and stats that must survive level transitions.