C# Monogame - System.IndexOutOfRangeException 与二维数组

C# Monogame - System.IndexOutOfRangeException with 2D array

我在使用 C# 时遇到问题,每当我 运行 在我的 类.

之一中使用 Draw 方法时,我总是收到 IndexOutOfRangeException

几个小时以来,我一直在努力找出问题所在,但一直没能找到确切的问题所在,而且我也没能在 Whosebug 上找到任何解决方案。

我是 C# 的新手(我只学了 3 或 4 天),所以解决方案可能会很明显。

Level.cs:

using Microsoft.Xna.Framework.Graphics;

namespace Game1 {
    class Level {
        public Tile[,] Tiles;

        public void Draw(SpriteBatch sb) {
            for (int x = 0; x < Tiles.GetLength(0); x++)
                for (int y = 0; x < Tiles.GetLength(1); y++)
                    if (Tiles[x, y] != null)
                        Tiles[x, y].Draw(sb, x, y);
        }

        public Level(int size) {
            Tiles = new Tile[size, size];
            for (int x = 0; x < size; x++)
                for (int y = 0; y < size; y++)
                    Tiles[x, y] = Tile.Tiles[0];
        }
    }
}

Tile.cs:

using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Game1 {
    class Tile {
        public static List<Tile> Tiles = new List<Tile>();

        Texture2D Image;

        public void Draw(SpriteBatch sb, int x, int y) {
            sb.Draw(this.Image, new Vector2(x * this.Image.Width, y * this.Image.Height), Color.White);
        }

        public Tile(Texture2D image) {
            this.Image = image;
            Tiles.Add(this);
        }
    }
}

试试这个:

 public void Draw(SpriteBatch sb) {
        for (int x = 0; x < Tiles.GetLength(0)-1; x++)
            for (int y = 0; x < Tiles.GetLength(1)-1; y++)
                if (Tiles[x, y] != null)
                    Tiles[x, y].Draw(sb, x, y);
    }

尝试检查 for 循环中的 y<... 而不是 if x<...

编辑:- 更改以下方法以检查第一个(外部)循环中的 x 和第二个(内部)循环中的 y

public void Draw(SpriteBatch sb) {
    for (int x = 0; x < Tiles.GetLength(0); x++)

        for (int y = 0; y < Tiles.GetLength(1); y++) //CHANGE THIS LINE

            if (Tiles[x, y] != null)
                Tiles[x, y].Draw(sb, x, y);
}