我遇到了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);
}
}
}
答案 0 :(得分:1)
尝试检查你的for循环中的y&lt; ...而不是x&lt; ...
编辑: - 更改以下方法以检查第一个(外部)循环中的namespace DrawShapes
{
class Rectangle : Shape
{
public int length;
public int width;
public Rectangle(int length, int width, string name) : base(name)
{
//this.angles = angles;
this.length = length;
this.width = width;
}
public override void DisplayArea()
{
Console.Write(name + "--");
Console.Write(length * width);
}
}
class Triangle : Shape
{
// public int angles;
public int width;
public int height;
public Triangle(int width, int height, string name) : base(name)
{
//this.angles = angles;
this.width = width;
this.height = height;
}
public override void DisplayArea()
{
Console.Write(name + "--");
Console.Write((width * height) / 2);
}
}
class Circle : Shape
{
public int radius;
public Circle(int radius, string name) : base(name)
{
this.radius = radius;
}
public override void DisplayArea()
{
Console.Write(name + "--");
Console.Write(3.22 * radius * radius);
}
}
}
和第二个(内部)循环中的x
:
y
答案 1 :(得分:-1)
试试这个:
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);
}