1

我有一个正在创建的 xna 游戏,它编译得很好,但是当它到达 spriteBatch.Begin(); 时会抛出一个 nullreferenceexception;在我的 spritemanager 类(这是一个可绘制的游戏组件)中。我认为 loadContent 没有运行,使 spritebatch 未初始化,但我不知道如何让它运行。

SpriteManager 加载内容代码:

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(Game.GraphicsDevice);  

        player = new Player(Game.Content.Load<Texture2D>("Images/asteroids_player"),
                            new Vector2(Game.Window.ClientBounds.X / 2, Game.Window.ClientBounds.Y / 2),
                            Vector2.Zero,
                            0f,
                            new Point( 27, 40 ),
                            new Point( 1, 1 ),
                            new Point( 1, 2 ));

        asteroidList = new List<Asteroid>();

        base.LoadContent();
    }

SpriteManager 绘制代码:

    public override void Draw(GameTime gameTime)
    {
        spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);  // error thrown here

        player.Draw(gameTime, spriteBatch);

        spriteBatch.End();

        base.Draw(gameTime);
    }

游戏1代码:

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    SpriteManager spriteManager;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // Creates and loads a SpriteManager to update/draw sprite objects
        spriteManager = new SpriteManager(this);
        Components.Add(spriteManager);

        base.LoadContent();
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here

        base.Draw(gameTime);
    }
4

1 回答 1

2

Initialize()在调用之前的方法中添加 SpriteManager 组件base.Initialize()

于 2013-02-13T20:34:08.900 回答