How UE saves global variables

        During the game, we often need to save some global variables, such as the player's total score, current life value, etc., and their values ​​remain unchanged after we switch levels. The SaveGame class object and GameInstance object are mainly used in UE.

        First, right-click to create a blueprint class, enter save to create a SaveGame blueprint class object, and name it MySaveGame; enter Gameins to create a GameInstance blueprint class object, and name it GameManager.

 

 

        Some global variables are defined in MySaveGame, such as scores and player health. A variable of type MySaveGame needs to be defined in GameManager, and the player's life value is used here for demonstration. Use CreateSaveGameObject to create the SaveGame class object when GameManager is initialized, and the type is specified as our custom MySaveGame.

At the same time, two functions are defined to set and get the player's life value.

 

 

 For the scene, I simply designed two scenes for switching.

 Next, design the player class object. For the thirdpersoncharacter blueprint that comes with the system, I don't plan to put the player function of my game in it, so I created a blueprint component class called MyPlayer. Select the third-person character in the scene, click the "Add Component" button below, and then select the first item "NewBlueprintScriptComponent", and create a blueprint component class named MyPlayer.

 In MyPlayer, you can define some player-related variables that will be used in your own game, such as life value, score, etc. At the same time, you need to define a GameManager class object to save the player's variables. The GameManager class object uses the CastTo node with the GetGameInstance function to obtain and set the variables.

 In the ThirdPersonCharacter class, a GameManger class object and a MyPlayer class object need to be defined. For the MyPlayer class object, use the GetComponentbyClass function to get it, because we used "AddComponent" at the beginning

         The function is tested below, and the test code is written in the ThirdPersonCharacer class. Press the 9 and dot keys on the small keyboard to switch between scenes, because the third-person character ThirdPersonCharacer exists in both scenes, so the following code can be executed in both scenes. Press the 7 key to reduce the player's life value by 1 and save it through GameManager. Press the 8 key to get the player's current life value and display it. After switching the scene, the function is normal.

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_34256136/article/details/128114491