GODOT 3.5.1报错:PoolVector2Array无法获取索引'0',求排查解决
问题分析与解决方案
错误原因
你遇到的 Invalid get index '0' (on base: 'PoolVector2Array') 错误,本质是访问了空数组或索引越界的数组,具体触发点如下:
随机索引计算逻辑错误
randi() % possible_destinations.size() - 1的运算顺序存在问题:randi() % size会生成0到size-1的整数,再减1会得到-1到size-2的值。当possible_destinations只有1个子节点时,会得到-1(虽然后端支持负索引取最后一个元素,但逻辑上不符合随机选目标的需求),如果possible_destinations为空,直接访问索引会直接崩溃。未检查路径数组有效性
navigation.get_simple_path()在以下场景会返回空数组或仅含起点的数组:- 起点与终点完全重合
- 导航系统无法找到可行路径
你的代码直接访问path[0],未做任何非空判断,导致索引越界报错。
路径更新时未判断数组长度
update_path()中直接调用path.remove(0),如果path已经为空,会触发索引越界错误。
修复后的代码
extends "res://Characters/NPCs/PlayerDetection.gd" onready var navigation = get_tree().get_root().find_node("Navigation2D", true, false) onready var destination = navigation.get_node("Destination") var motion var possible_destinations var path export var minimum_arrival_distance = 5 export var walk_speed = 0.5 func _ready(): randomize() possible_destinations = destination.get_children() # 初始化时先检查是否有可用目标 if possible_destinations.size() > 0: make_path() print(possible_destinations) func _physics_process(delta): # 只有当路径有效时才执行导航逻辑 if path and path.size() > 0: navigate() func navigate(): var distance_to_destination = position.distance_to(path[0]) if distance_to_destination > minimum_arrival_distance: move() else: update_path() func move(): look_at(path[0]) motion = (path[0] - position).normalized() * (MAX_SPEED * walk_speed) move_and_slide(motion) func update_path(): # 确保数组有元素再执行移除操作 if path.size() > 1: path.remove(0) elif path.size() == 1 and $Timer.is_stopped(): $Timer.start() func make_path(): # 先检查可用目标列表是否为空 if possible_destinations.size() == 0: print("警告:没有可用的目标点") return # 正确计算随机目标索引:0 到 size-1 var random_idx = randi() % possible_destinations.size() var new_destination = possible_destinations[random_idx] path = navigation.get_simple_path(position, new_destination.position) # 处理无法找到路径的情况 if path.size() == 0: print("警告:无法找到到目标点的路径") # 重新尝试生成路径 make_path() func _on_Timer_timeout(): make_path()
关键修复点说明
- 修正随机索引计算:用
randi() % possible_destinations.size()生成合法的数组索引,彻底避免越界问题。 - 增加非空判断:在
_physics_process、make_path中先检查数组是否有效,再执行后续逻辑,防止空数组访问。 - 安全更新路径:
update_path中先判断数组长度再执行移除操作,避免空数组操作报错。 - 处理寻路失败情况:当
get_simple_path返回空数组时,添加提示并重新尝试生成路径,提升鲁棒性。
内容的提问来源于stack exchange,提问作者Sylvain
相关产品推荐
相关产品推荐

