Good afternoon.
I’m developing a simple Tower Defense. Got to create health points (taken away when creeps reach the base) and coins (replenished for killing creeps, are taken away when building towers). Here, what interests: where usually such variables declare? After all, in fact, in the tower defence there is no player … we just move the camera (for her I have a separate GameModeBase and controller).
I think that this can be done as follows:
Use global variables in a separate .h file
Create a class for them (But what kind of class is this, this is no actor, right?)
It’s not recommended ot use global varbales in UE4 and not to mention UE4 reflection system does not support global variables. In case of UObject pointers in global variable you facing risk of having invalid pointer if object gets destroyed and you not null that varable after that, UE4 manages that for you if you use UPROPERTY(). Your object also can be garbage cleaned as UE4 won’t see you referencing it in global varable
What you trying to do should be in your GameMode class (whatever you use Base version or not). Heres quick list on where you should place data for what thing:
GameInstance - Data for entire game, most persistent and most global class in your arsenal. There might be different classes as persistent, but by assumptions of engine design for anything game related you should use this class. best place for persistent stats for your tower defense that effect multiple levels
GameMode - Data for single match, it resets on level changes or level restarts. This is best palce for your health information, as health in tower defense is for single match and should reset on level change or restart, alternativly you could use PlayerController, but if your game is single player then it makes no diffrence, or else players should share health then you should use GameMode.
PlayerController - Data for each single player, data here will be persistent even if pawn of player dies. Same as GameMode it resets on level change and level restart as well as player rejoining the game as it resets it PlayerController.
Pawn (any actor on level really) - Data for pawn, it get destroyed together with pawn this includes level restart and level switch ofcorse as pawn gets destroyed with the world.
It’s also worth noting that GameInstance is the first thing that gets initialised after the engine, and before BeginPlay or anything spawns (i.e. before GameMode, controllers and pawns).
So EventInit in GameInstance is the first opportunity you have to run code when the game runs.