【问题标题】:2D Array IndexOutOfRange Issue in Unity C# [closed]Unity C#中的二维数组IndexOutOfRange问​​题[关闭]
【发布时间】:2018-07-31 13:41:23
【问题描述】:

我有 35 个 Tile 对象,我试图将它们放入 2D 数组(和列表)中,但在填充数组时我不断收到 IndexOutofRange 错误。我使用的代码是:

private Tile[,] AllTiles = new Tile[5,7]; 
private List<Tile> EmptyTiles = new List<Tile>();

// Use this for initialization
void Start () {

    Tile[] AllTilesOneDim = GameObject.FindObjectsOfType<Tile> ();
    foreach (Tile t in AllTilesOneDim) {

        // Fill 2D Array AllTiles
        AllTiles [t.indRow, t.indCol] = t;
        // Fill List with all tiles
        EmptyTiles.Add (t);

    }
}

我应该注意,每个 Tile 对象都包含一个 indRow 0-4 之间的 int 和一个 indCol 0-6 之间的 int。

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    在将图块添加到二维数组之前,尝试添加一些防御性代码来检查范围。喜欢:

    int rows = AllTiles.GetLength(0);
    int cols = AllTiles.GetLength(1);
    
    int indRow = 0;
    int indCol = 0;
    
    foreach (Tile t in AllTilesOneDim) {
        indRow = t.indRow;
        indCol = t.indCol;
    
        if (indRow >= 0 && indRow < rows
            && indCol >= 0 && indCol < cols)
        {
            // Fill 2D Array AllTiles
            AllTiles[indRow, indCol] = t;
        }
    }
    

    使用调试器进入这条路径,看看你会发现什么。 indRow 和 indCol 值有时必须超出您指定的范围 5(0 到 4)和 7(0 到 6)。记住索引是从零开始的,长度返回项目的总数,所以我们必须减一才能找到正确的索引(或者像我在 if 语句中那样使用“索引小于行或列”)。

    GetLength() 方法:

    https://msdn.microsoft.com/en-us/library/system.array.getlength.aspx

    https://stackoverflow.com/a/4260228/8094831

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 2018-11-15
      • 2020-01-18
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多