对象引用未设置为对象#100的实例

时间:2011-10-12 15:18:36

标签: c# object reference null instance

我知道人们之前已经问过这个问题,但看起来他们的解决方案对我不起作用或者我做错了。

public class Sprite
{
    private Game m_game;
    private SpriteBatch m_spriteBatch;
    private string m_filename;
    private Texture2D m_texture;

    public Sprite(Game game, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice)
    {
        m_game = game;
        m_spriteBatch = spriteBatch;
        m_texture = new Texture2D(graphicsDevice, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height);
    }

    public void LoadSprite(string filename)
    {
        m_texture = m_game.Content.Load<Texture2D>(filename);
    }
}

当我将“tree”作为文件名传递时,LoadSprite会生成错误。 m_texture不为null,因为(试图)在构造函数中初始化它。 在主循环中使用对Content.Load的相同调用,但我想将其移动到Sprite类中。

treeTexture = Content.Load<Texture2D>("tree");

这在主循环中工作正常,因此它显示“树”文件存在。

谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:0)

m_game或m_game.Content可能为null。