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
Vector3values directly with==can fail due to floating-point precision quirks. UsingVector3.Distancewith a small threshold (like 0.01f) makes the "arrived" check far more reliable. - Proper loop handling: When
loopis 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
相关产品推荐
相关产品推荐

