0

I'm having an issue with C# where I keep getting an IndexOutOfRangeException whenever I run the Draw method in one of my classes.

I've been trying to figure out the problem for a couple of hours now, but I haven't been able to find the exact problem and I haven't been able to find any solutions on StackOverflow.

I'm new to C# (I've only been learning for 3 or 4 days), so the solution's probably going to be pretty obvious.

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);
        }
    }
}
Colm
  • 3
  • 5

2 Answers2

1

Try checking whether the y<... in your for loops instead of if x<...

EDIT:- Change following method to check x in first (outer) loop and y in second (inner) loop:

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);
}
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • 1
    This is the correct answer, but you've presented it very poorly. As it stands it's better suited a comment. Can I suggest that you flesh this out a little to show clearly what is wrong and what needs to be fixed? – Enigmativity May 29 '16 at 03:23
-1

Try 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);
    }
Juan Alvarez
  • 29
  • 1
  • 6