Persisting variables across Level Changes in Unreal Engine

- by

Today I’ve learnt about something called the Game Instance. This is an object that exists only once in our games, is created when the game starts, and torn down only when it ends. It persists across level changes, making it the ideal candidate for storing variables across level loads. It’s one of the first things that is created when we start a (stand-alone) game.

I had previously assumed the Game Mode would work this way, but alas it too is restarted when a new level is loaded. Thankfully, if you’re familiar with how to access your Game Mode from anywhere in your code, you’ll be pleased to hear that it’s just as easy to grab a reference to the Game Instance. Let me show you how to create one and reference it in this article.

Creating a Game Instance

Like any other object, create yourself a new Blueprint Class. The Game Instance won’t show up by default, so you’ll have to search for it.

Name it anything you like, perhaps MyGame (yeah… not very original I know). It’ll look like a circle in your Content Browser. If you open it up, it’ll look just like any other Blueprint Class without a viewport.

Setting your Game Instance

Much like the Game Mode, Default Pawn and Player Controller, the Game Instance needs to be setup in your Project Settings so that Unreal Engine uses it. You can find it at the very bottom on the Maps and Modes screen.

Referencing the Game Instance

Once setup, you can grab a reference to your Game Instance just like you would reference your Game Mode, using a cast. That’s important, otherwise Unreal Engine won’t let you access all those variables you’ll set on it.

Start with a generic Get Game Instance node, then drag its return value into a Cast To node. Then as “your game instance”, get/set any of the variables you need.

Usage Example

Here’s a usage example: if I wanted my current skeletal mesh and material to persist across a level load, I’ll create two such variables on the Game Instance. Just before the level is loaded, I’ll store those properties in the instance like so:

Now we load the next level.

The player character will reset to its default mesh and material, so we’ll grab those references in the construction script, overriding whatever is set in the viewport. That way, with every new level load, the previous skeletal mesh and material persists in the next level.

That’s it!

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site witout any pesky ads! More details here.

Add your voice