Skip to content

A4 - Variable Scope

There are three main variable scopes in GMS:

  • Local variables - declared with var and only accessible within the function or event where they are created
  • Global variables - prefixed with global., accessible throughout the game
  • Instance variables - declared without var, these are accessible anywhere within the object.

Here's an example of their declarations:

// Local variable, needed only temporarily within the current event
var dest_x = x + h_input * move_speed

// Global variable, accessible everywhere and existing for the duration of the game
global.score = 0

// Instance variable, accessible within all events of the instance and existing for as long as the instance exists
health = 5

More on Instance Variables

It is important to recognize that every instance of an object has it's own copies of the instance variables. So if you create an instance variable called health for a certain enemy type and then create ten instances of that enemy, there are really ten independent health variables in existence; one for each enemy.

GMS has several built-in instance variables, as documented here.

Your Task

Part 1

In assignment 3, go into the player's Step event and cut (CTRL+X) these lines form the top of the script:

// Settings
var move_speed = 4;
var collide_layers = ["solid_base", "solid_objects"]

Add a Create event to the player, and paste these lines into that file. Then, remove var from the start of each line to make these instances variables that will be accessible across all events.

This will not change anything functionally, but is slightly more efficient since these variables no longer get recreated on every step event.

Part 2

Take some time to familiarize yourself with some of the built-in instance variables.

In either one of your existing games or in a new game, try to using two or three of these that you haven't used yet in a script. Consider whether it makes sense to set these in the Create event, Step event, or somewhere else.

Part 3

Add a feature to your Assignment 3 that makes the player run when a key is being held down. Consider making use of the keyboard_check function, the move_speed variable we created, and the built-in instance variable image_speed (to increase the sprite's animation framerate while running). See here for more information on keyboard_check.