Search Unity

Array Index is out of Range

Discussion in 'Scripting' started by FFT15, Mar 18, 2017.

  1. FFT15

    FFT15

    Joined:
    Mar 18, 2017
    Posts:
    3
    Hi All

    I have an error that i stumbled across. The error is Index Out of Range Exception: Array Index is out of range.
    Below is the code


    for(int rowIndex = 0; rowIndex < currentRoom.Length + 1; rowIndex++)
    {

    string layoutRow = layoutRows[rowIndex].Trim('\t'); //Error here
    int numTiles = layoutRow.Length;

    for(int i = 0; i < numTiles; i++)
    {
    AddTile(layoutRow, rowIndex, i);
    }
    }


    I didnt understand what the error is or how to solve it. Can anyone help me please?

    Thanks
     
  2. Pengocat

    Pengocat

    Joined:
    Dec 7, 2016
    Posts:
    140
    It means that you are trying to use an array index that does not exist. Note that arrays start from index 0.
     
  3. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    First line should PROBABLY be:
    Code (csharp):
    1. for(int rowIndex = 0; rowIndex < currentRoom.Length; rowIndex++)
    This is assuming that currentRoom and layoutRows are the same length...
     
  4. FFT15

    FFT15

    Joined:
    Mar 18, 2017
    Posts:
    3
    It is complaining about this piece: int numTiles = layoutRow.Length;
     
  5. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Complaining how? You need to post the actual error for people to help you. ;)
     
  6. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    I would guess that the first for loop should be;

    Code (CSharp):
    1. for (int rowIndex = 0; rowIndex < layoutRows.Length; rowIndex++)
     
  7. FFT15

    FFT15

    Joined:
    Mar 18, 2017
    Posts:
    3
    Forgive me. Here is the error.
     

    Attached Files:

  8. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    Im pretty sure its .Count not .Length, also dont add 1 to your length, if it is length then thats why your going over your array.
     
  9. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    This line: "int numTiles = layoutRow.Length;" can not generate that error. I'd guess it's still coming from the line before that line, like in your original post. It's hard to know what the issue is without knowing what any of these variables mean, but if my fix didn't work, then maybe WarmedxMints is correct:

    Code (csharp):
    1. for (int rowIndex = 0; rowIndex < layoutRows.Length; rowIndex++)
    Index out of range means that "rowIndex" is a number outside the length of the array. If an array is length 3, then the only allowed index values are 0, 1, and 2. Anything 3 or higher will say "Index out of range."