Question: How do I create a new variable in GameMaker?


In GameMaker, you can create variables within objects or scripts to store data that can be referred to or changed throughout gameplay. Here's how to declare and initialize a new variable:

// To define a new local variable within a script or event: var myLocalVariable; myLocalVariable = 10; // To define a new instance variable within an object's event: myInstanceVariable = "Hello, World"; // To define a global variable, which is accessible from anywhere in the game: global.myGlobalVariable = 100;

Variables in GameMaker are not explicitly typed, meaning you don't need to specify what type of data the variable will hold; they are dynamically typed and can hold any type of value (e.g., strings, numbers, arrays). Local variables, defined with the var keyword, exist only within the scope where they're created — typically within a script or a code block of an event. They are automatically destroyed when the script or event finishes executing.

Instance variables, on the other hand, are attached to instances of objects and will exist as long as the instance exists. These variables are usually set in the object's events like the Create event or any other event and can be accessed using the dot notation (instance.variable) if needed from outside the instance.

Global variables are accessible from any instance or script in the game, and you must prefix them with global. to distinguish them from instance variables. Be careful with global variables, as their widespread accessibility can lead to confusing code if not managed carefully.

To ensure good programming practice, initialize your variables before using them. This helps avoid errors and makes it clear what the intended initial state of the variable should be.

Here's an example of initializing different types of variables within the Create event of an object:

// Create event for an object // Defining a local variable. Only accessible within this event. var initialHealth; initialHealth = 100; // Defining an instance variable. Accessible from all events within this object. health = initialHealth; // Defining a global variable. Accessible from any object or script. global.gameScore = 0;

Understanding the scope of these variables and their lifetime is key to managing data and states in your GameMaker project effectively.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.