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

Unity中路径点索引越界错误(ArgumentOutOfRangeException)如何解决?

Fix for ArgumentOutOfRangeException in Waypoint System

Let's break down why you're hitting this error first: when your object reaches the last waypoint, index increments to equal waypoints.Count (since collection indexes start at 0). The problem is your second if condition still tries to access waypoints[index] at that point—but the collection only goes up to index waypoints.Count - 1, hence the out-of-range error.

Here's how to fix it, with proper support for both looped and non-looped movement:

private void Update() {
    // Exit early if we have no waypoints or index is already out of bounds
    if (waypoints.Count == 0 || index >= waypoints.Count) {
        return;
    }

    // Move towards the current waypoint
    transform.position = Vector3.MoveTowards(transform.position, waypoints[index].position, speed * Time.deltaTime);

    // Check if we've reached the current waypoint (using a precision threshold)
    if (Vector3.Distance(transform.position, waypoints[index].position) < 0.01f) {
        index++;

        // Reset index to start if looping is enabled and we've reached the end
        if (loop && index >= waypoints.Count) {
            index = 0;
        }
    }
}

Key improvements made:

  • Guard clause at the top: Prevents any attempt to access invalid indexes by exiting early if there are no waypoints or we've already reached the end.
  • Robust position check: Comparing Vector3 values directly with == can fail due to floating-point precision quirks. Using Vector3.Distance with a small threshold (like 0.01f) makes the "arrived" check far more reliable.
  • Proper loop handling: When loop is enabled, we reset the index to 0 once we hit the last waypoint, instead of letting it climb out of bounds.

Also, a quick note for your Start method: if no GameObjects tagged "wp" exist, waypoints will stay empty—this fix handles that case gracefully to avoid crashes.

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:22:54