-2

I have 35 Tile objects and I'm trying to put them into a 2D array (and list) but I keep getting an IndexOutofRange error when populating the array. The code I'm using is:

private Tile[,] AllTiles = new Tile[5,7]; 
private List<Tile> EmptyTiles = new List<Tile>();

// Use this for initialization
void Start () {

    Tile[] AllTilesOneDim = GameObject.FindObjectsOfType<Tile> ();
    foreach (Tile t in AllTilesOneDim) {

        // Fill 2D Array AllTiles
        AllTiles [t.indRow, t.indCol] = t;
        // Fill List with all tiles
        EmptyTiles.Add (t);

    }
}

I should note that each Tile object contains an int for indRow between 0-4 and an int for indCol between 0-6.

dulongj
  • 307
  • 2
  • 17

1 Answers1

1

Try adding some defensive code to check the range before adding the tile to the 2D array. Like:

int rows = AllTiles.GetLength(0);
int cols = AllTiles.GetLength(1);

int indRow = 0;
int indCol = 0;

foreach (Tile t in AllTilesOneDim) {
    indRow = t.indRow;
    indCol = t.indCol;

    if (indRow >= 0 && indRow < rows
        && indCol >= 0 && indCol < cols)
    {
        // Fill 2D Array AllTiles
        AllTiles[indRow, indCol] = t;
    }
}

Use the debugger to step into this path and see what you find. The indRow and indCol values must sometimes be outside of your specified ranges of 5 (0 to 4) and 7 (0 to 6). Remember indexes are zero based and the Length returns the total number of items so we must subtract one to find the correct index (or use "index less than rows or cols" like I did in the if statement).

GetLength() Method:

https://msdn.microsoft.com/en-us/library/system.array.getlength.aspx

https://stackoverflow.com/a/4260228/8094831

green.maru
  • 61
  • 1
  • 6