0

好吧,我有一个非常奇怪的问题。我现在正在用 C#/MonoGame(在 Linux 上)编写一个简单的游戏。我正在尝试玩SoundEffect. 当我打电话时Play()(即使它已正确加载到LoadContent()方法中)。NullReferenceException它与消息一起抛出一个Object Reference not set to an instance of an object

这是代码的结构

public class MyGame : Game
{
    // ..
    private SoundEffect _sfx;

    public PingGame ()
    {
        // ...
    }

    protected override void Initialize ()
    {
        // ...
    }

    protected override void LoadContent ()
    {
        // ...

        // No errors here on loading it
        _sfx = Content.Load<SoundEffect>("noise.wav");
    }

    protected override void Update (GameTime gameTime)
    {
        // ...

        if (playSound)
        {
            // This is where the error is thrown
            _sfx.Play();
        }

        // ...
    }

    protected override void Draw (GameTime gameTime)
    {
        // ..
    }
}
4

3 回答 3

0

错误信息说明了一切。在您调用Update (GameTime gameTime)对象时_sfx未初始化。

不可能知道你想如何设计你的游戏,但你可以通过改变下面的代码来测试它,你将不再有空引用异常。这可能不是您希望设计代码的方式,但它可以让您了解哪里出了问题以及如何修复它。请参阅下面的代码。

protected override void Update (GameTime gameTime)
{
    // ...

    if (playSound)
    {
        // This is where the error is thrown
        // THIS ENSURES WHEN THIS METHOD IS INVOKED _sfx is initialized.

        _sfx = Content.Load<SoundEffect>("noise.wav");
        if(_sfx != null){
          _sfx.Play();
        }
    }
    // ...
}
于 2016-08-21T21:30:35.423 回答
0

我的盲目猜测是(因为您没有包含代码):

  • GraphicsDeviceManager不是在构造函数内部创建的(需要在调用 base.Initialize() 之前创建)
  • base.Initialize()或者你忘记在你的方法中调用Initialize方法。
于 2016-08-21T21:48:57.893 回答
0
protected override void Update(GameTime gameTime)
{
    // ...

    if (playSound)
    {
        if (_sfx == null)
        {
            Content.Load<SoundEffect>("noise.wav");
        }
        _sfx.Play();
    }
}
于 2016-08-27T23:08:41.740 回答