我不明白自己在做什么错:

public void Draw(GameTime gameTime) // in ScreenManager
{
    SpriteBatch.Begin(SpriteBlendMode.AlphaBlend);
    for (int i = 0; i < Screens.Count; i++)
    {
        if (Screens[i].State == Screen.ScreenState.HIDDEN)
            continue;

        Screens[i].Draw(gameTime);
    }
    SpriteBatch.End(); // null ref exception
}


SpriteBatch本身不为null。

更多背景信息:

public class MasterEngine : Microsoft.Xna.Framework.Game
{

    public MasterEngine()
    {
        graphicsDeviceManager = new GraphicsDeviceManager(this);
        Components.Add(new GamerServicesComponent(this));

        // ...

        spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice);

        screenManager = new ScreenManager(assets, gameEngine, graphicsDeviceManager.GraphicsDevice, spriteBatch);
    }

//...

   protected override void Draw(GameTime gameTime)
    {
        screenManager.Draw(gameTime); // calls the problematic method
        base.Draw(gameTime);
    }
}


我是否无法正确初始化某些内容?

更新:

作为实验,我尝试对MasterEngine的构造函数进行此操作:

spriteBatch = new SpriteBatch(graphicsDeviceManager.GraphicsDevice);

spriteBatch.Begin();
spriteBatch.DrawString(assets.GetAsset<SpriteFont>("calibri"), "ftw", new Vector2(), Color.White);
spriteBatch.End();


这不会导致NRE。嗯...

更新2:这确实会导致NRE:

protected override void Draw(GameTime gameTime)
{
    spriteBatch.Begin();
    spriteBatch.End(); // boned here
    //screenManager.Draw(gameTime);
    base.Draw(gameTime);
}

最佳答案

您不应该在Game类或SpriteBatch类的构造函数中创建DrawableGameComponent,因为不能保证GraphicsDevice当时已正确初始化。 (实际上,您最终可能会使用空的图形设备来初始化它们:P)

将您的SpriteBatch创建移动到覆盖的LoadContent方法中

与您的ScreenManager相同,您在错误的位置传入了GraphicsDevice。如果您的ScreenManager继承自DrawableGameComponent,那么您仍然应该可以从其中访问GraphicsDevice属性,您可以在屏幕的LoadContent方法中使用该属性来加载ScreenManager所需的任何内容。

希望能有所帮助。

关于c# - XNA:什么会导致SpriteBatch.End()抛出NRE?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2572474/

10-10 17:42