Help, ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection

Help, I am having an issue with ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. I am trying to have an NPC roam between waypoints, the NPC walks to the first waypoint and then freezes. I can’t find where the index error is, the debugger says that it is on line 46. I am not sure if it is the animation or if it is the waypoints themselves.

It means you’re trying to access a collection by its indexer with a value that’s out of bounds. Namely your wayPoints array on line 46.

This can include trying to access an empty collection. So, you will want to debug how many elements are in the collection, why it might be empty if it is, and also guard your code around having no waypoints either.

Thanks, but I am confused when you say “Guard your code around having no waypoints”. Are you saying to change it so the NPC wouldn’t rely on waypoints?

Since wayPoints being empty is what’s causing the issue here, add a check to your if statement on line 45 to make sure wayPoints.Length > 0 so you only index in if it actually has elements.

1 Like

‘Guarding’ your code means writing it to anticipate potential situations where an error would otherwise be thrown, and use that to prevent said code from running.

Eg:

if (agent.remainingDistance <= agent.stoppingDistance)
{
    if (waypoints.Count > 0)
    {
        int waypointIndex = Random.Range(0, waypoints.Count);
        Vector3 waypointPosition = waypoints[waypointIndex].postion;
        agent.SetDestination(waypointPosition);
    }
    else
    {
        Debug.LogWarning("Agent has no waypoints!");
        // maybe shut down agent?
    }
}

A common thing to do in a number of situations.

1 Like