Question: How do you create and use an array of objects in GameMaker?


In GameMaker, an array is a data structure that can hold a collection of values, which includes instances of objects. To create and use an array of objects, follow these steps:

  1. Creating an Array of Objects: You declare an array and then assign object instances to its elements. In GameMaker, object instances are referred to by their instance IDs, which are essentially numbers.
// Create an empty array var objectArray = []; // Add instances to the array objectArray[0] = instance_create_layer(x, y, "Instances", obj_Enemy); objectArray[1] = instance_create_layer(x, y, "Instances", obj_Player); // ... and so on for as many objects as you need
  1. Accessing Array Elements: To access or modify an element within the array, you refer to it by its index.
// Access the first object in the array (index 0) var firstObject = objectArray[0]; // Move the first object firstObject.x += 10;
  1. Iterating Over an Array of Objects: If you want to perform operations on every object in the array, you use a loop.
// Loop through each object in the array for (var i = 0; i < array_length(objectArray); ++i) { var objInstance = objectArray[i]; // Perform some action with objInstance objInstance.x += 5; // For example, move each object to the right }
  1. Multidimensional Arrays: If necessary, you can also create multidimensional arrays to store objects, which can be useful for grid-based games or complex data structures.
// Create a two-dimensional array var gridArray = array_create(10, undefined); for (var i = 0; i < 10; ++i) { gridArray[i] = array_create(10, undefined); for (var j = 0; j < 10; ++j) { gridArray[i][j] = instance_create_layer(i * 32, j * 32, "Instances", obj_Tile); } }
  1. Dynamic Arrays: GameMaker's arrays are dynamic, meaning they can grow and shrink during runtime. You can add items using the array_push function or remove them with array_delete.
// Push a new object onto the end of the array array_push(objectArray, instance_create_layer(x, y, "Instances", obj_Collectible)); // Delete the second object in the array array_delete(objectArray, 1);

Remember to manage your object instances properly to avoid memory leaks or errors. This means you should free up resources when they are no longer needed, such as using instance_destroy() to remove an object instance from the game when it's no longer in use.

Was this content helpful?

Start building today

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