0

i have got problem with sounds in unity. This is my code:

[RequireComponent(typeof(AudioSource))]

public class SoundManager : MonoBehaviour { public static SoundManager instance;

private AudioSource source;
public Dictionary<SOUND_TYPE,AudioClip> sounds;
public enum SOUND_TYPE
{
    DEATCH,
    CATCHED
}

// Use this for initialization
void Start()
{
    source = GetComponent<AudioSource>();

    loadSounds();
}

// Update is called once per frame
void Update ()
{
}

public void playSound(SOUND_TYPE type)
{
    source.clip = sounds[type];
    source.Play();  
}

public void loadSounds()
{
    //loading sounds
    sounds.Add(SOUND_TYPE.DEATCH, Resources.Load<AudioClip>("Sounds/AccelerationLow"));
}

}

And i have an error at line with source.Add().

Error: NullReferenceException: Object reference not set to an instance of an object

I don't know what is going on and how can i repair it.

Abhishek Aryan
  • 18,857
  • 8
  • 44
  • 57
mvxxx
  • 115
  • 6

2 Answers2

1

You forgot a constructor of sounds:

public Dictionary<SOUND_TYPE,AudioClip> sounds = new Dictionary<SOUND_TYPE,AudioClip>();
0

It means that public Dictionary<SOUND_TYPE,AudioClip> sounds is not initialized or has the value of null initialized. To initialize this dictionary create a constructor or initialize this dictionary in the start method sinds the source is initialized there to.

To initialize an empty dictionary use:

Dictionary<SOUND_TYPE,AudioClip> sounds = new Dictionary<SOUND_TYPE,AudioClip>();

void Start()
{
    source = GetComponent<AudioSource>();
    sounds = new Dictionary<SOUND_TYPE,AudioClip>();`
    loadSounds();
}

public void loadSounds()
{
  Start()
  //loading sounds
  sounds.Add(SOUND_TYPE.DEATCH, Resources.Load<AudioClip>("Sounds/AccelerationLow"));

}
Timon Post
  • 2,353
  • 12
  • 25