0

我既是 C# 又是 XNA 菜鸟,我有点卡住了。

在我的 Game1 类中,我添加了一个 SoundEffect 对象。在这个类中,我可以使用 [objectname].Play(); 播放声音。例如

public SoundEffect newSound;
newSound.Play();

但是,我有另一个代表精灵的类。如果我尝试从该类中发出声音,则会收到空引用异常错误。例如(在我的精灵类中):

Game1 newGame = new Game1();
newGame.newSound.Play();

我知道这是一个常见的错误。我知道它与初始化对象实例有关。我的问题是,虽然我对此进行了广泛的研究,并找到了解决此错误的其他解决方案,但我不明白为什么我会收到它。

这就是为什么我没有粘贴我的完整代码。我想知道的是,谁能指出我可以向我解释这应该如何工作的教程或文章的方向?我宁愿在不完全理解问题所在的情况下让这个错误消失。

非常感激任何的帮助。谢谢

4

2 回答 2

2

问题是,您的精灵需要访问运行游戏循环的 Game1实例,并且初始化了SoundEffect. new Game1()正在给你一个不同的实例,它没有处于正确的状态来做任何事情。

通常在这里做的是在你的 Sprite 类上有一个构造函数参数或一个可设置的属性。我假设您的 Game1 类在某个时候创建​​了您的精灵:

Sprite s = new Sprite();

And instead, you want to be able to pass the instance of Game1 to it:

Sprite s = new Sprite(this);

And you'll need to modify your sprite class so that it a) takes this new argument in its constructor, and b) stores this value into a field, so that you can access it later.

I'd be able to flesh this out a bit more if I could see your whole Sprite class, but I can appreciate it may be a little large to post here.

于 2011-09-26T07:52:12.247 回答
1

这就像假设很多事情一样......

你有 Game1 类,它是在更新/绘制无限循环中运行以保持游戏的主类......

然后你有另一个类,我们称之为 Enemy,在 Game1 的 Update 方法中,你调用 Enemy.PlaySound()

在 Enemy::PlaySound 中,您想播放在 Game1 的 LoadContent 中初始化的声音,例如

public void PlaySound()
{
 Game1 newGame; //like assuming that with this you are pointing to the instance of Game1 that it's running and since it's not the instance of that class and it's not even initialized there is the NullReferenceException.....(I think)
newGame.NewSound.Play(); //Assuming againt that we have a property to access the NewSound
}

这里有很多长镜头......但问题有点不清楚......

编辑 - 第一次评论后

那也行不通

它会像这样工作

public class Enemy
{
 ....

    public void PlaySound(Game1 newGame)
    {
        newGame.NewSound.Play();
    }
 ....
}

但是将 Game1 作为参数传递给 Enemy Methods 并不是一个好习惯……IMO

有很多好书、教程和框架可以指导你......

于 2011-09-26T07:37:08.300 回答