C#从2d数组加载地图获取System.NullReferenceException

时间:2014-06-22 18:52:40

标签: c# xna-4.0

当我尝试启动时,我得到System.NullRefrenceException没有idéa为什么 我的代码是:

Tile.cs:

class Tile : Sprite
{
    public bool IsBlocked { get; set; }

    public Tile(Texture2D texture, Vector2 position, SpriteBatch batch, bool isBlocked)
        : base(texture, position, batch)
    {
        IsBlocked = isBlocked;
    }

    public override void Draw()
    {
        SpriteBatch.Draw(Texture, Position, Color.White);
    }
}

这是我生成瓷砖的基本代码

这是我的地图加载器

MapLoader.cs

class MapLoader
{
    List<Texture2D> tileList = new List<Texture2D>();
    public Tile[,] Tiles { get; set; }
    public Texture2D TileTexture { get; set; }
    public SpriteBatch SpriteBatch { get; set; }
    static int TileWidth = 64;
    static int TileHeight = 64;
    int mapWidth;
    int mapHeight;

    private int[,] map = 
    {
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, 
        { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,}, 
        { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,}, 
        { 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1,}, 
        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,}
   };

    public MapLoader(SpriteBatch spritebatch, Texture2D normaltile, Texture2D nulltile, Texture2D SharpTile, Texture2D MovingTile)
    {
        tileList.Add(nulltile);
        tileList.Add(normaltile);
        tileList.Add(SharpTile);
        tileList.Add(MovingTile);
        mapWidth = map.GetLength(1);
        mapHeight = map.GetLength(0);
        for (int x = 0; x < mapWidth; x++)
        {
            for (int y = 0; y < mapHeight; y++)
            {
                    Vector2 tilePosition =
                        new Vector2(TileWidth * tileList[map[x, y]].Width, TileHeight * tileList[map[x, y]].Height);
                    Tiles[x, y] =
                        new Tile(tileList[map[x, y], tilePosition, spritebatch, map[x, y] != 0);
            }
        }
    }
    public void Draw()
    {
        foreach (var tile in Tiles)
        {
            tile.Draw();
        }
    }
}

错误发生在这行代码中

Tiles[x, y] = new Tile(tileList[map[x, y], tilePosition, spritebatch, map[x, y] != 0);

我知道我填写它。

1 个答案:

答案 0 :(得分:0)

如果得到NullReferenceException,则访问值为null的变量。 可能的候选者:上面一行中的所有变量,可以在构造函数中访问。

显然,在MapLoader的构造函数中,您不能创建数组Tile[,] Tiles。仅声明属性不会在堆上创建实际值。

查看C#的数组语法规则!

更新你的构造函数并添加这一行`Tiles = new Tile [mapWidth,mapHeight];在第一个for-loop之前,你会没事的!