Ova

How do you create a global variable in GameMaker?

Published in GameMaker Variables 5 mins read

In GameMaker, you create a global variable in one of two primary ways: by explicitly using the global. prefix or by declaring it with the globalvar keyword. Both methods allow data to be accessed and modified from anywhere in your game project, making them ideal for managing game-wide information.

Understanding Global Variables in GameMaker

Global variables are a powerful tool for managing data that needs to be accessible across different objects, rooms, and scripts throughout your entire game. Unlike instance variables (which belong to a specific object instance) or local variables (which exist only within a specific script or event), global variables maintain their value and state universally. They are perfect for storing information like the player's score, game settings, current game state, or any other data that needs to be globally synchronized.

Methods to Create Global Variables

There are two main approaches to defining global variables in GameMaker Language (GML):

1. Using the global. Prefix

This is the most common and recommended method for creating and referencing global variables. When you assign a value to a variable prefixed with global., GameMaker automatically creates it as a global variable if it doesn't already exist.

  • How it works: You simply type global. followed by your desired variable name.

  • Syntax: global.variableName = value;

  • Example:

    // In an object's Create event (e.g., obj_GameManager)
    global.playerScore = 0;       // Initialize player score
    global.musicVolume = 0.7;     // Set initial music volume
    global.gamePaused = false;    // Track game pause state
    
    // Later, in another object or event (e.g., player collision)
    if (global.gamePaused == false) {
        global.playerScore += 100; // Add to score
    }
    
    // Changing music volume in a settings menu
    global.musicVolume = audio_get_master_gain(audio_group_new(ALL));

Advantages:

  • Clarity: Explicitly indicates that the variable is global, making your code easier to read and understand.
  • Consistency: Encourages a uniform way to access global data throughout your project.
  • Simplicity: No prior declaration is strictly needed; assignment automatically creates it.

2. Using the globalvar Declaration

The globalvar keyword allows you to explicitly declare one or more variables as global within a specific script or event. This is similar to how you use the var keyword for local variables but declares the variable with a global scope.

  • How it works: You use globalvar followed by a list of variable names, separated by commas. After declaration, these variables become globally accessible.

  • Syntax: globalvar variable1, variable2, ...;

  • Example:

    // In a dedicated initialization script (e.g., scr_globals_init)
    globalvar playerLives, enemyCount, maxLevel;
    
    // Now, assign initial values (preferably using the global. prefix for consistency)
    global.playerLives = 3;
    global.enemyCount = 0;
    global.maxLevel = 5;
    
    // In other parts of your game, you would still access them using:
    // global.playerLives -= 1;
    // show_debug_message("Current level: " + string(global.maxLevel));

Important Note: While globalvar declares a variable as global, GameMaker's best practice is to always explicitly refer to global scope using the global. prefix when accessing or modifying these variables throughout your project. This maintains clarity and consistency, regardless of how the global variable was initially declared.

Comparison of Global Variable Creation Methods

Feature global.variableName = value globalvar variableName
Creation Implicit on first assignment Explicit declaration, followed by assignment
Access Always requires global. prefix Can be accessed without global. in the same scope after declaration, but global. prefix is highly recommended for project-wide consistency and clarity.
Readability Very clear, explicit global scope at all times Declares intent, but subsequent access without global. can be ambiguous.
Common Use Most frequently used for both creation and access Useful for batch declarations in an initialization script.

Best Practices for Using Global Variables

To keep your GameMaker project organized and maintainable, follow these guidelines when working with global variables:

  • Initialize Early: Always initialize your global variables at the very beginning of your game's lifecycle. A common approach is to create a dedicated "Game Manager" object (obj_GameManager) and initialize all global variables in its Create event, or use a specific "initialization script" (e.g., scr_init_globals) called once at game start.
  • Use Descriptive Names: Give your global variables clear, descriptive names (e.g., global.playerHealth instead of global.ph). This significantly improves code readability for yourself and others.
  • Avoid Overuse: While convenient, excessive reliance on global variables can lead to "spaghetti code" and make debugging challenging. If a piece of data only concerns a few specific objects, consider using instance variables or passing data as arguments to functions/scripts.
  • Centralized Management: Create a single, dedicated script (e.g., scr_globals_init) where all your global variables are declared and initialized. This makes them easy to locate, modify, and understand.

When to Use Global Variables

Global variables are best suited for:

  • Player State: global.playerScore, global.playerHealth, global.playerLives.
  • Game State: global.gameState (e.g., MENU, PLAYING, PAUSED), global.currentLevel.
  • Game Settings: global.musicVolume, global.sfxVolume, global.difficultySetting.
  • Shared Resources: Global arrays or lists managing available items, enemies, or collected artifacts.

By understanding and applying these methods and best practices, you can effectively use global variables to create robust and manageable game logic in GameMaker.