簡體   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