This is an intermediate level Unreal Engine 4 tutorial on how to save and read variables. This is useful for keeping values even when the game is not running. In my examples, I am saving GUI settings that were acquired through a settings menu in the main menu. Also, my saving process is done in my custom GameInstance blueprint, because that blueprint contains all of my variables that need to be saved. GameInstances are constant throughout the entire game, no matter what the map or GameMode is. One important thing to note is that I have code that applies all of my settings in the all of the game mode’s blueprint’s BeginPlay node. This will ensure that the settings are constant when switching maps and game modes.
How to save variables/settings:
- Create a SaveGame blueprint. This blueprint shouldn’t have any code. It should only store variables that you will create. Create an identical variable in SaveGame for every single variable that you need to save. Also come up with a slot name for your SaveGame object. If you are making a game that has multiple saves, make sure the names are unique for each save. My slot name is GameSave, and my custom SaveGame blueprint is also called GameSave.
- Find the place where you will be putting your saving code. For me this is the Shutdown event in the GameInstance.
- Use the CreateSaveGameObject node with your custom SaveGame class to make a new SaveGame object.
- Cast the return value to your custom SaveGame. This will allow us to modify the variables in your custom SaveGame.
- Set the values of the variables in your custom SaveGame with the values you need to save.
- Finally, use the node, SaveGametoSlot, with the unique SaveGame name you came up with, and the SaveGame object that was created and modified, to save your custom SaveGame to a file.
How to read variables/settings:
- Find a place where you are going to put your reading code. For me, this is the GameInstance Init event.
- First step is check if we have a SaveGame from previous runs of the game. Use the DoesSaveGameExist node with the name you came up with to check if there is a SaveGame. If true, then we read the variables. Otherwise, we do not do anything. For me, I will let the defaults for each variables which are stored in GameInstance be the actual values if there is no SaveGame.
- Use the LoadGameFromSlot with the name you came up with to read the saved values.
- Cast the SaveGame object you got from LoadGameFromSlot to the SaveGame blueprint you made. By doing this, you can access your variables through your custom SaveGame object.
When the settings menu is created in my code, it will read the values from the custom GameInstance and change state of the sliders, textbox, checkbox, and other GUI objects.
Thanks for reading and I hope this helps!