In this lesson, you will learn how to maintain vital player data across level transitions by leveraging the GameInstance class.
Understanding the GameInstance Lifecycle
In Unreal Engine, most objects—such as your Character, Controller, or HUD—are destroyed whenever the game world changes (like loading a new map). This reset is great for memory management, but it creates a challenge: how do you keep track of a player's score, inventory, or health when moving from "Level 1" to "Level 2"?
The GameInstance is the solution to this problem. Unlike an Actor, the GameInstance is created when the game initializes and is only destroyed when the application closes. It acts as a "long-term memory" container that survives every world reset.
Implementing Persistent Variables
To persist data, you define variables directly inside your GameInstance blueprint (or C++ class). Because this object exists independently of the current level, you can read and write to it from any actor currently loaded in the world.
For example, if you want to store a PlayerScore integer, you would add that variable to your custom GameInstance subclass. In your gameplay logic, you retrieve it using the "Get Game Instance" node:
// C++ logic to update score in the persistent instance
UMyGameInstance* MyGI = Cast<UMyGameInstance>(GetGameInstance());
if (MyGI)
{
MyGI->PlayerScore += 100;
}
When the level finishes and a new one begins, the GameInstance remains in memory. The new level simply calls "Get Game Instance" again, retrieves the existing PlayerScore variable, and your HUD displays the carry-over total instantly.
Best Practices
While the GameInstance is perfect for transient cross-level data, remember it is not a save-file system. If the player closes the game application, the GameInstance memory is wiped. Use it specifically for managing state transitions during a single play session. By decoupling your state from the volatile Actors in your level, you ensure your game flows seamlessly from one environment to the next without losing progress.
Key Takeaway: Use the GameInstance to store data that must persist through level changes, as it is the only object that survives the transition between different gameplay worlds.