c# - 使用 C# 访问二维数组时出错

标签 c# multidimensional-array unity3d grid 2d

我是 Unity3D 和 C# 的新手。我正在尝试在 2d 数组中存储一些网格位置,但是我遇到了

数组索引超出范围

错误,我不知道为什么:

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.

以下是我寻求帮助的其他一些资源: http://wiki.unity3d.com/index.php/Choosing_the_right_collection_type

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

最佳答案

您有一个 6x2 的二维数组,而不是一个 2x6 的数组。如果您想通过 array[row, column] 访问数组,则您在初始化中指定的每个“子数组”都是一个“行”。

因此,例如,myArray[0, 1] 是 375 - 第一个“行”的第二个元素,即 { 0, 375 }

基本上,您需要调整数组初始化或数组访问。所以如果你真的想要一个 2x6 数组,你需要:

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

...或者您可以保留现有的初始化,并访问 myArray[4, 1]

C# 规范是这样解释的:

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;

关于c# - 使用 C# 访问二维数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30972771/

相关文章:

c# - 添加 Authorize 属性时 Web api 核心返回 404

C# - 在按下键时从字符串中删除最后一个字符

c# - 如何在C#中获取设备的当前位置

php - 通过特定值的最大值从多维数组返回值

c# - Unity3d - 如何获取 Animator 的图层 --> 子状态 --> 状态名称哈希?

Android 项目在发布版本中生成过多的 DEX 文件

android - 在 Android 上的 Unity3D 中将网站渲染为纹理

c# - 如何解决RDLC中的 "Report item not linked to Dataset"错误?

javascript - 在 Javascript 中对值对进行排序

javascript - 根据名称将多个数组拆分为变量