2012-01-07 78 views
1

我的影片从网上例子得出一个基本的声音管理器类:http://www.xnawiki.com/index.php?title=Basic_Sound_Manager_For_XNA_GS_3.0NullReferenceException异常的声音管理器类,简单的C#XNA

的问题是,每当我打电话LoadSound读取(字符串ASSETNAME,串assetPath)方法,我得到一个NullReferenceException。我猜这意味着内容管理器找不到指定的引用并返回null。 虽然这对我来说没有任何意义,因为我参考的内容文件夹中确实有声音。在我将健全的管理转移到一个单独的课程之前,它很有效

下面是我的SoundManager类中的类相关的代码片段:

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”,并且在content/sounds/ding.wav(资产名称冲突)处存在声音。我在这里认真看不到任何问题。如果有任何人可以看到的任何奇怪的范围问题,请帮助,我即将到期。

+0

您能否发布完整的异常,包括堆栈跟踪请 – 2012-01-07 19:22:35

+0

如果LoadSound在Initialize之前被调用,则内容将为空。否则,问题可能在另一种方法中,在这种情况下,堆栈跟踪将很有用。 – 2012-01-07 19:26:34

回答

3

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

+0

或''Initialize'被调用时'game.Content'为null。 – 2012-01-07 19:26:51

+0

是的,LoadSound在Initialize之前被调用,谢谢。 – 2012-01-07 19:33:16

+0

高兴地帮助:) – 2012-01-07 19:34:22