IndexOutOfRangeException ????? what is the error

IndexOutOfRangeException: Array index is out of range

this is the error im getting for line 28 of my patrol.cs
here is line 28 -

transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);

id appreciate any help cheers!

Error is pretty clear - currentPoint >= patrolPoints.Length

Check the part when you’re setting currentPoint and check there if it’s at the end of the path.

1 Like

// Update is called once per frame
void Update () {
if (currentPoint >= patrolPoints.Length)
{
currentPoint = 0;
}

if (transform.position == patrolPoints[currentPoint].position)
{
currentPoint++;
}

transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
}
}

sorry, a bit of a noob at this, using this code for a college project.
what do i have to do to this to stop the error?

Indexes are 0 based, so if you have an array of length 5, the indexes range from 0 to 4.

You’re allowing currentPoint to reach patrolPoints.Length, which is out of range since the index is 0 based. Using my example, patrolPoints[5] is out of range because valid indexes are 0 to 4.

So looking at your code where you’re trying to reset currentPoint back to 0 will reveal the problem.

Specifically you have a subtle logical bug in your code. You are correctly checking to make sure you index doesn’t go to far, but then you increasing the index AFTER The check with this code:

if (transform.position == patrolPoints[currentPoint].position)
{
currentPoint++;
}

If currentPoint was = patrolPoints.Length-1 it will pass your check… but then increment out of bounds in the next code. You just need to flip the positions of those two blocks of code, so you out of bounds check happens after you might possibly increment it.

1 Like

thanks man, helped me a lot, cant believe it was that simple.
cheers man!