Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error accessing 2d array with c#

I am new to Unity3D and c#. I am tinkering with storing some grid positions within a 2d array however I've run into

the array index is out of range

error and I don't know why:

public int[,] myArray; 

    myArray = new int[,]{
        {0,375},
        {75,300},
        {150,225},
        {225,150},
        {300,75},
        {375,0}
    };

    Debug.Log(myArray[1,4]); // array index is out of range... why? I expected to get 75.

Here are some other resources I was looking at for help: http://wiki.unity3d.com/index.php/Choosing_the_right_collection_type

https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx

like image 479
fruitloops Avatar asked Mar 16 '23 16:03

fruitloops


1 Answers

You have a 2D array which is 6x2 - not one which is 2x6. Each "subarray" you're specifying in the initialization is one "row", if you think of accessing the array by array[row, column].

So for example, myArray[0, 1] is 375 - the second element of the first "row", which is { 0, 375 }.

Basically, you need to pivot either your array initialization, or your array access. So if you really want a 2x6 array, you'd need:

myArray = new int[,] {
    { 0, 75, 150, 225, 300, 375 },
    { 375, 300, 225, 150, 75, 0 }
};

... or you could keep the existing initialization, and access myArray[4, 1].

The C# specification explains it like this:

For a multi-dimensional array, the array initializer must have as many levels of nesting as there are dimensions in the array. The outermost nesting level corresponds to the leftmost dimension and the innermost nesting level corresponds to the rightmost dimension. The length of each dimension of the array is determined by the number of elements at the corresponding nesting level in the array initializer. For each nested array initializer, the number of elements must be the same as the other array initializers at the same level. The example:

 int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};

creates a two-dimensional array with a length of five for the leftmost dimension and a length of two for the rightmost dimension:

 int[,] b = new int[5, 2];

and then initializes the array instance with the following values:

b[0, 0] = 0; b[0, 1] = 1;
b[1, 0] = 2; b[1, 1] = 3;
b[2, 0] = 4; b[2, 1] = 5;
b[3, 0] = 6; b[3, 1] = 7;
b[4, 0] = 8; b[4, 1] = 9;
like image 89
Jon Skeet Avatar answered Mar 23 '23 22:03

Jon Skeet