我正在编写一个脚本,该脚本使用过程生成来用树对象填充地图。在代码中,我放置了一个锚树,然后检查其周围的基本方向,将树放置在四个开放空间中的任何一个中。然后,代码使用choose()函数选择四棵新树之一作为新的锚对象。漂洗并重复直到所有的树都摆好为止。
一切正常,直到我选择了新的锚树。这部分大部分时间都有效,但偶尔会崩溃,并显示一条错误,指出“在读取前未设置局部变量”,这很有意义,因为它并不总是具有属于它的对象,尽管这种情况很少见。 。由于代码在重复循环中进行迭代,因此几乎应该始终有一个有效的对象可供引用。
我现在拥有的代码是我提出的创可贴解决方案,迄今为止效果最好。我只是在努力找出如何解析未定义的变量,以使choice()函数不会出错。我希望可以将一个变量分配给select();然后通过if instance_exists循环运行它,但仍然会出错。
我的感觉是我盯着这个眼睛太久了,需要一双崭新的眼睛。感谢您的帮助!
下面是一张成功状态的小相册:https://imgur.com/a/aDRzEDO
repeat(forest) {
var anchor_x = floor(anchor_tree.x/32);
var anchor_y = floor(anchor_tree.y/32);
var above_y = floor(anchor_tree.y/32) - 1;
var below_y = floor(anchor_tree.y/32) + 1;
var right_x = floor(anchor_tree.x/32) + 1;
var left_x = floor(anchor_tree.x/32) - 1;
if ds_grid_get(tree_place, anchor_x, above_y) == 0 && forest > 0 { //above check
var a = instance_create_layer(anchor_tree.x, anchor_tree.y - y_off, "Instances", obj_tree);;
ds_grid_add(tree_place, anchor_x, above_y, 1);
if a.x > room_width || a.y > room_height {
instance_destroy(a);
} else {
forest -= 1;
}
}
if ds_grid_get(tree_place, anchor_x, below_y) == 0 && forest > 0{
var b = instance_create_layer(anchor_tree.x, anchor_tree.y + y_off, "Instances", obj_tree);
ds_grid_add(tree_place, anchor_x, below_y, 1);
if b.x > room_width || b.y > room_height {
instance_destroy(b);
} else {
forest -= 1;
}
}
if ds_grid_get(tree_place, right_x, anchor_y) == 0 && forest > 0{
var r = instance_create_layer(anchor_tree.x + x_off, anchor_tree.y, "Instances", obj_tree);
ds_grid_add(tree_place, right_x, anchor_y, 1);
if r.x > room_width || r.y > room_height {
instance_destroy(r);
} else {
forest -= 1;
}
}
if ds_grid_get(tree_place, left_x, anchor_y) == 0 && forest > 0{
var l = instance_create_layer(anchor_tree.x - x_off, anchor_tree.y, "Instances", obj_tree);
ds_grid_add(tree_place, left_x, anchor_y, 1);
if l.x > room_width || l.y > room_height {
instance_destroy(l);
} else {
forest -= 1;
}
}
///Running into trouble here////
anchor_tree = choose(a,b,r, l);
}
编辑: 我相信我可能已经找到了解决方案。至少,它还没有崩溃。 在每个instance_destroy(x)之后;我加x =没有人;像这样;
if ds_grid_get(tree_place, anchor_x, above_y) == 0 && forest > 0 { //above check
var a = instance_create_layer(anchor_tree.x, anchor_tree.y - y_off, "Instances", obj_tree);;
ds_grid_add(tree_place, anchor_x, above_y, 1);
if a.x > room_width || a.y > room_height {
instance_destroy(a);
a = noone; <------ here
} else {
forest -= 1;
}
}
然后我完成这个
anchor_tree = choose(a,b,r, l);
if anchor_tree = noone {
while anchor_tree = noone {
anchor_tree = choose(a,b,r, l);
}
}
如果发现失败状态,我将进行更新。
更新: 仍然失败。
解决方案更新: 在重复循环开始之前,将变量(a,b,r,l)初始化为等于初始的anchor_tree。这样,如果检查失败,则可以使用有效值循环返回以重试。