限制数组大小2D(C#UNITY)

时间:2018-06-05 05:18:28

标签: c# android unity3d

大家好,可以像这个例子一样限制数组大小

enter image description here

现在我只想展示其中的6个。

到目前为止,我所做的是

CustomClass

const int MAX = 104;  // = 8 decks * 52 cards / 4cardsoneround
const int Y = 6;

int[,] arrayRoad = new int[Y, X];

 public int[,] GetRoad(int x) {
    arrayRoad = new int[x, 6];
    return arrayRoad;
}

现在我在 MainClass 上显示它

ScoreBoard bsb = new ScoreBoard();

private void Road()
{
    bsb.makeRoad(history); // Road
    int[,] arrayRoad = bsb.GetRoad(6); //<--- sample value 6

    string s = "";
    for (int y = 0; y < arrayRoad.GetLength(0); y++)
    {
        //just 27 for now

        for (int x = 0; x < 28; x++)
        {
            s += string.Format("{0:D2}",arrayRoad[y, x]);
            s += ".";
        }
        s += "\n";
    }
    Debug.Log(s);
}

此代码的问题在于它给了我Array out of index

这可能吗?

更新

public int[,] GetRoad(int x = MAX,int y = Y) {
    arrayRoad = new int[y, x];

    return arrayRoad;
}

Max = 104Y = 6

中的位置
int[,] arrayRoad = bsb.GetRoad(12,6); //12 rows and 6 in height

    string s = "";
    for (int y = 0; y < arrayRoad.GetLength(0); y++)
    {
        for (int x = 0; x < arrayRoad.GetLength(1); x++)
        {
            s += string.Format("{0:D2}",arrayRoad[y, x]);
            s += ".";
        }
        s += "\n";
    }
    Debug.Log(s);
}

在执行更新代码之前,我已经拥有了所有这些值

enter image description here

现在,当我在这里执行更新的代码时,我得到了什么

enter image description here

预期结果必须是此

enter image description here

在那个黑色标记内部,必须显示那些十二列,因为我在我的

上声明了
int[,] arrayRoad = bsb.GetRoad(12,6);

2 个答案:

答案 0 :(得分:2)

请注意:

 public int[,] GetBigEyeRoad(int x) {
    arrayRoad = new int[x, 6]; // <-------------
    return arrayBigEyeRoad;

你要将数组第二维的长度固定为6。

    for (int x = 0; x < 28; x++)
    {
        s += string.Format("{0:D2}",arrayBigEyeRoad[y, x]); // <------------

在那里,您尝试在阵列的第二维上访问最多28的索引。 Out of Range错误来自于此。

答案 1 :(得分:0)

我在这里做的是将旧数组复制到新数组,就像下面的代码一样

int[,] arrayBigRoadResult = new int[6, x];
//copy manually the element references inside array
for (int i = 0; i < 6; i++)
{
    for (int j = 0; j < x; j++)
    {
        arrayBigRoadResult[i, j] = arrayBigRoad[i, j];
    }
 }
return arrayBigRoadResult;

然后通过这样调用

int[,] arrayRoad = bsb.GetRoad(12);

它只显示12列和6行:)

相关问题