1

我正在创建一个游戏,目前我有 3 个类,greenpaddle、ball 和 Game1。

当我运行我的游戏时,调试器跳到我spriteBatch.Begin(); 并说NullReferenceException Unhandled。这是我的 Game1.cs:

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

    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Ball ball;
    GreenPaddle gPaddle;
    Texture2D BackGround;


    public Game1()
    {

        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.PreferredBackBufferHeight = 500;
    }

    protected override void Initialize()
    {
        gPaddle = new GreenPaddle();
        ball = new Ball(gPaddle);
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        BackGround = Content.Load<Texture2D>("pongBG");
        gPaddle.LoadContent(Content);
        ball.LoadContent(Content);
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        gPaddle.Update(gameTime);//Error Line
        ball.Update(gameTime);

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();//Error Line
        spriteBatch.Draw(BackGround, new Vector2(0f, 0f), Color.White);
        gPaddle.Draw(spriteBatch);
        ball.Draw(spriteBatch);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

不知道怎么回事,我从来没有遇到过这种情况。

4

1 回答 1

1

因为你初始化了 spritebatch...

spriteBatch = new SpriteBatch(GraphicsDevice);

null...除非您的其他课程之一正在更改它,否则它不应该是。

你可以尝试的事情:

- 在加载内容中放一个断点,我不知道为什么它不会被调用,但只是检查以防万一,确保它LoadContent()被调用。

-重建您的项目并确保您的更改被保存。


...当我写这个答案并在我的机器上测试代码时,我终于发现了错误。如果其他人有这些问题之一,我会留下上面的建议。

你没有调用base.Initialize你的Initialize()方法。这个方法调用了内部 XNA 的东西,这会导致你LoadContent()被调用。

调用方法也是一个好主意,您应该始终在任何被覆盖base.LoadContentLoadContent()方法上调用基本方法。

于 2013-07-28T01:41:04.870 回答