Storing widget and other singleton like references.

by on

I decided to take a break for a moment to talk about something that is not very well described by others.


While taking our newest title from single-player to multi-player, we ran into issues with how we were storing references to things like our main menu widget.


There are several answers on the internet that recommend saving these into places like the PlayerController, PlayerState, GameMode, GameState, LevelBlueprint, etc.


Just trying to get something together we went with the PlayerController. Which worked fine for single-player; however, in multi-player, the menu appears again because the player controller is destroyed and recreated. There are more issues when you take into account making sure only the local player is activating a widget.


The level blueprint might work well if you were only planning on having a single title/game, for the main menu reference. Start adding in the options menu, and you have to reference it in every level blueprint, things start not to make sense pretty quick and are not very DRY.


Our solution, extend the GameInstance class, it is created when the game is started and only destroyed when the game is closed.


Which makes it pretty much the only logical choice, add in the ease of getting the GameInstance from nearly anywhere in code or blueprints and it makes you wonder why people would recommend anything else?


Another thing that's going to save us a bunch of time is creating a template GameInstance that has this boilerplate code ready to go for future games.


So as a further recommendation, only store references to things that you will use in every game when you create the first extension of GameInstance.


Then extend that extension with the references for that specific game. You can then easily copy and paste the first extension into your next game with minor changes.


It also makes a great place to spawn and store references to things like an HttpService Actor, music, etc.


After you make your custom GameInstance don't forget to switch to it in Project Settings -> Maps and Modes, scroll to the bottom.


It's also convenient to make a Blueprint from the GameInstance to easily change values if you end up doing that make sure to select the Blueprint version from the drop-down.


Comments 0
No comments have been left yet.