【问题标题】:NullReferenceException in a sound manager class, simple C# XNA声音管理器类中的 NullReferenceException,简单的 C# XNA
【发布时间】:2012-02-05 00:55:37
【问题描述】:

我有一个源自在线示例的基本声音管理器类:http://www.xnawiki.com/index.php?title=Basic_Sound_Manager_For_XNA_GS_3.0

问题是,每当我调用 LoadSound(string assetName, string assetPath) 方法时,都会收到 NullReferenceException。我猜这意味着内容管理器找不到指定的引用并返回 null。 但这对我来说没有意义,因为我引用的内容文件夹中肯定有声音。在我将声音管理转移到单独的课程之前,它已经奏效了。

这是我的 SoundManager 类的相关代码 sn-p:

public static class SoundManager
{
    // Class variables
    static Dictionary<string, SoundEffect> sounds = new Dictionary<string,
                                                             SoundEffect>();
    static Song currentSong;
    static ContentManager content;
    static float soundVolume = 1f;

    // Initialize: Load the game's content manager.
    public static void Initialize(Game game)
    {
        content = game.Content;
    }

    public static void LoadSound(string assetName)
    {
        LoadSound(assetName, assetName);
    }

    // Load a sound from a passed name into the dictionary
    public static void LoadSound(string assetName, string assetPath)
    {
        sounds.Add(assetName, content.Load<SoundEffect>(assetPath));
    }
}

异常发生在行

sounds.Add(assetName, content.Load<SoundEffect>(assetPath));

在 Game1 的 Initialize() 方法中,我正在调用:

SoundManager.Initialize(this);

在 Game1 的 LoadContent() 方法中,我调用了以下代码:

SoundManager.LoadSound("collision", "Sounds\\collision");

Content.RootDirectory 是“内容”,并且在 content/sounds/ding.wav 中存在声音(资产名称冲突)。我真的看不出这里有任何问题。如果任何人都可以看到任何奇怪的范围问题,请帮忙,我的最后期限即将到来。

【问题讨论】:

  • 能否发布完整的异常,包括堆栈跟踪
  • 如果在 Initialize 之前调用 LoadSound,内容将为空。如果不是,则问题可能出在另一个方法中,在这种情况下,堆栈跟踪将很有用。

标签: c# xna nullreferenceexception


【解决方案1】:

如果 NRE 在您的代码中,则必须是 content 为空:即,在 LoadSound 之前没有调用 Initialize。使用断点或一些快速调试来检查是否是这种情况。

【讨论】:

  • game.Content 在调用Initialize 时为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2011-12-01
相关资源
最近更新 更多