繁体   English   中英

C#Monogame-带有2D数组的System.IndexOutOfRangeException

[英]C# Monogame - System.IndexOutOfRangeException with 2D array

我在C#中遇到问题,每当我在一个类中运行Draw方法时,我都会不断获取IndexOutOfRangeException。

我已经尝试找出问题了几个小时,但是我一直无法找到确切的问题,而且我也无法在StackOverflow上找到任何解决方案。

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

尝试检查for循环中的y <...而不是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);
}

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM