I keep getting this message in the console and I have done research and can not figure out why. IndexOutOfRangeException: Index was outside the bounds of the array.
NavAgent.FindDestination () (at Assets/ProjectFolders/Script/NavAgent.cs:21)
NavAgent.Start () (at Assets/ProjectFolders/Script/NavAgent.cs:16)
When I click it takes me to this bit of my code:
void FindDestination()
{
Vector3 newTravelPosition = myNavPoints[navIndex].transform.position;
myNavAgent.SetDestination(newTravelPosition);
}
I am new at programming and developing. The code it is working with is to move my navigation agent from one navpoint to the other. The array is there so I can add different navpoints for the character to move toward.
If this is all your code and you only change your navIndex inside OnTriggerEnter, the only case when your line 21 can cause an index out of bounds exception is when your array is empty. That means the Length is 0 and there is no valid index at all.
If that’s the case you might just want to add a check inside FindDestination if the array has elements
void FindDestination()
{
if (myNavPoints == null || myNavPoints.Length == 0)
{
Debug.LogWarning("myNavPoints array is empty or not defined");
return;
}
// [ ... ]
}
This will ensure the code where you use your index will not run when you don’t have any elements. If the index could be changed through other means which might cause the index to be out of bounds you might want to implement a check like this instead:
if (myNavPoints == null || navIndex < 0 || navIndex >= myNavPoints.Length)
This will check both, the array length and also ensures that the index is in a valid range. This implicitly checks the array length since if the navIndex is 0 and the array length is 0 it will also early exit the method