数据结构(Data structures)


在游戏中,你经常需要精确且有序地存储信息。比如,你可能需要保存一个人携带的刀具列表或你希望存储一组需要访问的地区。Now, you can use the arrays for this, but if you want to do more complicated operations, like sorting the data or searching for a particular item, you need to write large pieces of GML code which can be slow to execute, difficult to debug and a real pain to write!

To remedy this, GameMaker Studio 2 has a number of built-in data structures that can be accessed through specialist functions. There are six different types of data structure available, each one having its own benefits depending on the type of information that you are looking to store and how you wish to manipulate it later: stacks, queues, lists, maps, priority queues, and grids.

Essentially, all data structures work in the same way - You create a data structure and store its index value in a variable. 然后,你可以使用这个索引值在其他函数中进行调用操作。最后,一旦你用完记得要销毁这个数据结构以将其从内存中移除。You can use as many of the structures at the same time as you need, and all structures can store both strings and real values.

NOTE: As with all dynamic resources, data structures take up memory and so should always be destroyed when no longer needed to prevent memory leaks which will slow down and eventually crash your game.
IMPORTANT! When you create a data structure, the index value to identify it is an integer value starting at 0. This means that different data structures can have the same index value, so if in doubt you should be using the ds_exists function before accessing them. Also note that indices are re-used, so a destroyed data structure index value may be used by a newly created one afterwards, and we recommend that you set any variable that holds a DS index to -1 after having destroyed the data structure.


关于不同数据结构的具体信息可以在以下章节找到:

  1. 堆栈(Stacks)
  2. 队列(Queues)
  3. 列表(Lists)
  4. 映射表(Maps)
  5. 优先队列(Priority Queues)
  6. 栅格(Grids)

在你实际使用数据结构之前,你还需要了解一点,在四舍五入的情况下有时候你得到的结果可能会与预期相悖。使用下列函数来修改数据精度可以解决该问题:

以下函数则用于检查某个数据结构是否存在

最后,你同样可以使用 数组来保存数据。你可以在下面这节中查看更多关于数组的内容:

  1. 数组