简体   繁体   中英

System.NullReferenceException in monogame

I have some problems with creating a soundmanager.cs in monogame in c#. There is a System.NullReferenceException in my add function. Here is the important part of my SoundManager

public sealed class SoundManager
{
    public static Dictionary<string, SoundEffect> mSoundEffects;
    public static ContentManager mContentMgr;

    public SoundManager(ContentManager contentManager)
    {
        mContentMgr = contentManager;
        mSoundEffects = new Dictionary<string, SoundEffect>();

    }

    public static void AddSoundEffect(string soundName)
    {
        if (!mSoundEffects.ContainsKey(soundName))  //System.NullReferenceException error mSoundeffects = null, soundName = "energyCircleSound"
        {
            mSoundEffects.Add(soundName, mContentMgr.Load<SoundEffect>(soundName));
        }
    }
}

In another class I want to load the sound with the following code.

 public static SoundEffect mEffectSound;
 private static SoundEffect energyCircle;
 public override void LoadAssets()
    {
        // Load sound effects

        SoundManager.AddSoundEffect("energyCircleSound");


        mEffectSound = Soundmanager.mSoundEffects["energyCircleSound"];
    }
    [...]
    private void CastEnergyCircle(Vector2 position)
    {
        if (AreaOfEffect.Cooldown > 0)
        {
            // Nothing happens yet if cooldown hasn't expired
            return;
        }
        AreaOfEffect energyCircle = new AreaOfEffect(50, 50, 2000, 500, position, mEffectTexture, mEffectSound);
        mEffects.Add(energyCircle);
        energyCircle.Sound.Play();
        //SoundManager.PlayEnergyCircle();
        energyCircle.DealDamage(mTargets);
        RemoveDeadTargets();
    }

There is no problem with areofEffects. Everything works perfect without the sound manager. I don't understand this error. I think mSoundeffects should not be null, because i load something in it with LoadAsset(). Could anybody help me, please?

Your constructor is an instance constructor and likely never called, that is why your static method fails when it relies on instance methods being called previously.

I don't know whether you want to use this as a static class or an instance. Either way, decide for one and go with it. Mixing it can be very confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM