【问题标题】:Limit the array size 2D (C# UNITY)限制数组大小 2D (C# UNITY)
【发布时间】:2018-06-05 05:18:28
【问题描述】:

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

现在我只想展示其中的 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);

【问题讨论】:

  • 运行这段代码会发生什么?有可能吗?
  • 它给了我一个Out of Range 错误。
  • arrayBigEyeRoad又是arrayRoad的错字吗?
  • @RodrigoRodrigues 错字太多我很抱歉。天啊
  • 预期结果是什么?

标签: c# android unity3d


【解决方案1】:

注意这一点:

 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 错误就是由此而来。

【讨论】:

  • 在您发布答案之前,请查看我对我之前所做的修改
  • 检查我答案的最后一部分:您正在将数组的 SECOND 维度固定为 GetRoad 方法中的 6。稍后,在 for 循环中,您尝试使用高于 6 的值迭代 SECOND 维度。这就是问题
  • 实际上解决了这个问题,但现在的问题是我的二维数组上的值已经消失了。嗯。
【解决方案2】:

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

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 行:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2012-05-13
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多