首页 > 解决方案 > 限制数组大小 2D (C# UNITY)

问题描述

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

在此处输入图像描述

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

到目前为止我所做的是

自定义类

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);
}

在执行更新代码之前,我早先拥有所有这些值

在此处输入图像描述

现在,当我执行更新的代码时,这就是我得到的

在此处输入图像描述

预期的结果一定是这样

在此处输入图像描述

在那个黑色标记里面,只有那十二列必须显示,因为我在我的

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

标签: c#androidunity3d

解决方案


请注意:

 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而来。


推荐阅读