sexta-feira, 24 de junho de 2016

BP Compendium 2: Game Instance

Game Instance

Before loading a new level, the current level is unloaded and the variables used by the current level are removed from memory. When the new level is loaded, the variables related to the level such as GameMode, PlayerController and Pawn are created with default values. This means that if there are values in the variables that need to be preserved for the next level, they must be saved before leaving the current level and then loaded into the new level.

Another option to preserve variable values between the levels is by using the "GameInstance" class. An instance of this class is created at the beginning of the game and is only removed when the game is closed. To create a Blueprint of this type search for "gameinstance" in the "AllClasses" category.

After creating the Blueprint of the type "GameInstance" you must configure the project to use this new "GameInstance". Access the main editor menu option: Edit-> ProjectSettings-> Maps & Modes. A Blueprint called "BP_GameInstance" was created to be used in this project.

As an example it was created in "BP_GameInstance" a variable named "Time Spent in Game" to save the time a person has spent in the game. The image below is a custom event that shows how to access this variable from another Blueprint.

Click to enlarge

Use the "Get Game Instance" function to get the reference to the "GameInstance" being used by the project. But this reference is of the type "GameInstance" and to access the variable "Time Spent in Game" you must use a reference of the type "BP_GameInstance" which is obtained using the "Cast to BP_GameInstance" action.