When you declare and initialize a variable in the Create Event of an object, such variable is not a global variable, but an instance one. That means, as it occurred to you, that every time the object is instantiated, its instance variables are set to their default value.
If you don't want such variables to be reinitialized every time the room starts, you can try two different approaches:
- Global variables: instead of having your
food
, stamina
, and other variables declared in the Create Event of obj_Global_Variables
, you can make them variables of the special object global
. This way, they will be accessible by any instance of your application, and won't be reinitialized until you close and reopen your game manually, or the function game_restart()
is executed. You can declare them in the Game Start Event of the very first instance created in the very first room ran in your game. Otherwise, you can put an instance in charge of declaring them in its Create Event, and make sure such code script is executed only once.
- Persistent object: you can make your object
obj_Global_Variables
persistent. A persistent object is not destroyed when moving from a room to another, thus restarting a room won't have such object being destroyed and instantiated once again. And that means its instance variables won't be reinitialized, and will store they current values until the instance is somehow destroyed. The persistent
variable can be set both in the Object window and via GML code.
Both strategies are good enough for your goals, although many programmers discourage using global variables (not only in GM:S, but also in C, C++, Java, and many other programming languages) because of them being global. A global variable is accessible by any class or instance, and that means if you are not aware of code execution order among instances toward such variables, you may get unexpected results. On the other hand, if the only reason you are using global variables is not losing its value during execution, if only one instance at time is in charge of reading/writing such variables, then it would be acceptable to use them.
Also, never forget global variables in GM:Studio can't be deallocated, because you can't simply destroy the special instance global
. So, make global as few variables as possible, or you'll be wasting memory space.