Object variables
When you add variables to an object, any instance of the object put on the scene or created during the game will have those variables attached to it. For example, you can have a variable called `Life`` representing the health of the object (or you can use the Health extension).
Object variables are variables which are:
- stored in memory for as long as a specific instance of an object exists,
- is different for each instance of the object.
They're useful for storing data associated with individual instances of an object, such as the amount of health an enemy has, ammo, etc... They're deleted from memory when the instance is removed from the scene.
Note
The terms object variable, instance variable, and object instance variable are used interchangeably.
Creating object variables
- Open the Scene editor.
- Open the object editor of the object that you want to add the variable to.
- Open the Variables tab.
In the editor, choose "Add a variable", then enter a name, choose a data type and, optionally, enter a default value for the variable (this will be the value used when the scene starts).
Tip
Variable names should not contain dots (periods), commas or spaces. Other characters are also reserved by GDevelop. If you use something forbidden, GDevelop will automatically correct the name you've entered.
Using object variables in expressions
You can use object variables in expressions. Just write the name of the object, followed by a dot then the name of the variable to use it in a formula. For example: Player.RemainingPoints.
When to use object variables
Object variables are the right choice when the data is specific to one instance. For example:
- An enemy's current health — each enemy on the screen needs its own value. While a variable can work, the Health behavior is usually a better choice for managing health.
- A projectile's damage — each projectile may carry a different power level depending on the weapon that fired it.
- A collectible's point value — each coin or gem can hold a different reward.
If every instance always shares the same value, a scene variable or a global variable is usually simpler.
Tip
Object variables can also hold structures or arrays, which lets you store complex per-instance data (for example, an inventory attached to a character object) without needing any additional variables.