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


In GameMaker Studio 2, starting from version 2.3.0, you can use structs to create lightweight objects. An array of structs is a powerful way to manage collections of complex data. Here's how you can create and use an array of structs:

  1. Defining a Struct: First, define a struct that will represent the individual elements within your array.
function player_struct(name, score) { return struct { name: name, score: score, increaseScore: function (amount) { this.score += amount; } }; }
  1. Creating an Array of Structs: You can then initialize an array and fill it with instances of your struct.
var players = []; players[0] = player_struct("Alice", 1000); players[1] = player_struct("Bob", 2000); // You can also add to the array dynamically players[| players.length] = player_struct("Charlie", 1500);
  1. Accessing Elements: Access individual structs in the array using standard indexing.
var firstPlayerName = players[0].name; // "Alice" var secondPlayerScore = players[1].score; // 2000
  1. Modifying Structs in an Array: To modify a struct in an array, directly access its properties or call its functions.
players[0].increaseScore(500); // Increases Alice's score by 500 // Direct property modification players[1].score += 300; // Increases Bob's score by 300
  1. Iterating Over an Array of Structs: Loop through each element using a for loop.
for (var i = 0; i < array_length(players); ++i) { var player = players[i]; show_debug_message( + ": " + string(player.score)); }

Remember to handle memory carefully when working with arrays of structs. While structs are generally more performant than full instances for storing simple, structured data, they still require memory management, especially when creating and deleting many structs in large arrays.

Was this content helpful?

Start building today

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