how do i make a global variable in c++?

Id like to make a global variable which points to my UGameInstance object.

How should i do that?

There’s a UGameplayStatics class that has things like that for you.




// Just pass it any actor or UObject contained in the World you want the GameInstance for.
UGameplayStatics::GetGameInstance(...)



I recommend this, as you don’t have to include the GameplayStatics header this way.


GetWorld()->GetGameInstance();

I also recommend getting the Game Instance as Strife.x pointed out.

It is bad practice to use global variables, because it creates dependencies in the code, which are harder to maintain. Should the value of your variable in your game change at any time, you would have to make sure, that your global variable is being set correctly at the right moment, otherwise, you may access an object which no longer exists or is otherwise valid. Using generally functions like:


GetWorld()->GetGameInstance()

takes automatically care of such a thing to not happen. Use scoped/local variables instead to keep only within a block a reference to your Game Instance.

However, if you still want to know how to use global variables, this is how it’s done in C++:

https://www.tutorialspoint.com/What-…s-in-Cplusplus
https://www.tutorialspoint.com/why-a…in-c-cplusplus (besides the url, this one tells how to declare them)

If you want to create “global variables” in Unreal Engine, the best approach is, to place them inside your Game Instance, then always get the game instance and from it your “global variable”. This is not exactly what a global variable is in C++, but it achieves a similar goal. They can be rather called persistent variables.

Your game instance effectively will serve as a so-called “Inversion of Control” container to your game. It will have the only responsibility to maintain these variables and provide always the correct value this way, even if a variable may change (similar to how the other objects work already which are referenced by the Game Instance). I use this approach for everything which persists throughout the game or the level.

2 Likes