How to persist state between levels in Unreal Engine and a simple example game project

Kristian Kristola

Kristian Kristola

· 5 min read
flutter

Photo by Brecht Corbeel on Unsplash

This post describes one way how you can make a global state in Unreal Engine that is preserved between levels and can be accessed from anywhere in the game including blueprints and C++.

This post was written with Unreal Engine 4, but the same principles should apply to Unreal Engine 5 as well. The editor UI might just look a bit different.


First, make a new project, for example with the "First Person Template", where you can walk around and shoot boxes.

alt text


Open project settings.

alt text


Under Maps & Modes, go to the setting "Game Instance Class" and override it with your own class by pressing the plus button.

alt text

The Game Instance Class is a class that is created once when the game starts and is preserved the whole time the game is running.


Give the new class some name and add some variables in it that you want to be preserved between levels. For example, here I'm adding an integer type variable that holds the number of how many boxes have been shot. alt text


 

 

That's it!

The rest of the steps are just an example of how you can make a full working example of a game that utilizes the global state.

It's mainly meant for people who are new to Unreal Engine and want to see how to use the various parts of the engine to make a simple game that uses a global state.

 

 


In the blueprints of the game, find the place where a projectile hits a box and add nodes that get the game instance you just created and reads the int variable, increments it by one and writes it back. alt text


Create a new widget that shows the number of boxes shot and put it on the screen.


Put the following function in the widget blueprint. How it works is, that on every frame it returns what the widget is supposed to be displaying. This function gets the Game Instance and casts it to an instance of the class holding the global state you created earlier, and gets the "Shot Boxes Count" variable from there. alt text


Create the following trigger in the level. When the player walks into the trigger, the level changes to another level. alt text


Now start the game and shoot a couple of boxes and see that the number of boxes shot increases. alt text


Walk into the trigger and go to the next level. alt text


Notice that the number of boxes shot is preserved between levels. alt text

Kristian Kristola

About Kristian Kristola

I'm a consultant and software developer with a strong foundation in game programming and the ability to adapt to new technologies and languages. Please feel free to contact me at:@
Copyright © 2024 Kiuas Games. All rights reserved.
Made by Osuuskunta Kiuas Games
Powered by Vercel

This website uses Google Analytics to collect anonymous information such as the number of visitors to different pages.