You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GML访问全局数组报索引越界错误Variable Index [8] out of range

GML数组越界报错修复方案

报错Variable Index [8] out of range [0]由两处逻辑错误导致:

  • 你定义的global.map是一维数组,不是二维数组。代码里的换行仅为排版效果,GML不会自动将每行内容拆分为子数组,当前数组是64个数值平铺的结构,不支持数组[索引][索引]的二级访问方式。
  • 循环创建方块实例时,没有给每个方块存储自身对应的网格坐标,所有方块都直接读取边框对象Obj_Border上的循环变量ii、jj。双层循环执行结束后,ii和jj的最终值都是8(循环终止条件为<8,最后一次自增后变量值为8),用8作为数组索引访问长度为8的数组时,就会触发越界。

具体修改步骤

  1. 将global.map改为标准二维数组,替换Obj_BorderCreate事件中原有的数组定义代码:
global.map = [
    [0,0,0,1,1,0,0,0],
    [0,0,0,1,1,0,0,0],
    [0,0,0,1,1,0,0,0],
    [1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1],
    [0,0,0,1,1,0,0,0],
    [0,0,0,1,1,0,0,0],
    [0,0,0,1,1,0,0,0]
]
  1. 修改Obj_BorderCreate事件中的双层循环逻辑,创建方块实例后,给每个方块单独绑定自身对应的网格坐标,不要共用边框对象上的循环变量:
for (ii=0; ii<8; ii++) {
    for (jj=0; jj<8; jj++) {
        // 创建网格边框
        instance_create_layer(x + (ii*sprite_get_width(Spr_Hoop)),
                              y + (jj*sprite_get_height(Spr_Hoop)),
                              "Instances",
                              Obj_Hoop)
        // 创建方块,缓存新生成的实例ID
        var square_ins = instance_create_layer(x+1 + (ii*(sprite_get_width(Spr_Square)+2)),
                              y+1 + (jj*(sprite_get_height(Spr_Square)+2)),
                              "Instances",
                              Obj_Square)
        // 给当前方块写入专属的网格坐标
        square_ins.grid_x = ii;
        square_ins.grid_y = jj;
    }
}
  1. 修改Obj_Square的Draw事件,读取自身存储的网格坐标获取地图对应值,不再访问Obj_Border上的循环变量:
if (global.map[grid_x][grid_y] == 1) {
    image_blend = c_white
} else { 
    image_blend = c_black
}
draw_self()

若运行时提示grid_x/grid_y变量未定义,在Obj_Square的Create事件中添加两行初始化代码即可:

grid_x = 0;
grid_y = 0;

内容的提问来源于stack exchange,提问作者Andrew Luce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 13:15:40