Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

IndexOutOfRangeException ????? what is the error

Discussion in 'Scripting' started by HyperPickle, Nov 7, 2016.

  1. HyperPickle

    HyperPickle

    Joined:
    Oct 10, 2016
    Posts:
    3
    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!
     
  2. Kalladystine

    Kalladystine

    Joined:
    Jan 12, 2015
    Posts:
    227
    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.
     
    Kiwasi likes this.
  3. HyperPickle

    HyperPickle

    Joined:
    Oct 10, 2016
    Posts:
    3
    // 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?
     
  4. Dave-Carlile

    Dave-Carlile

    Joined:
    Sep 16, 2012
    Posts:
    967
    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.
     
  5. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    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:
    Code (CSharp):
    1. if (transform.position == patrolPoints[currentPoint].position)
    2. {
    3. currentPoint++;
    4. }
    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.
     
    HyperPickle likes this.
  6. HyperPickle

    HyperPickle

    Joined:
    Oct 10, 2016
    Posts:
    3
    thanks man, helped me a lot, cant believe it was that simple.
    cheers man!