Why is this small code generating null reference error? (Null reference when trying to add values to a dictionary using foreach)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AudioClipsHolder : MonoBehaviour {

    public List<AudioClip> audioClipList;
    public Dictionary<string, AudioClip> audioClipDic;

    void Start()
    {
        foreach (AudioClip audioClip in audioClipList)
        {
            Debug.Log(audioClip.name);
            audioClipDic.Add(audioClip.name, audioClip);
        }
    }


}

I drag some audios to the audioClipList using the editor. The “Debug.Log(audioClip.name)” works and will print the name of the first clip. Then an error is generated when the code gets to “audioClipDic.Add(audioClip.name, audioClip)”

The error is “NullReferenceException: Object reference not set to an instance of an object”

Can anyone tell me what is wrong with this code?

Thanks

1 Answer

1

You need to initialize the Dictionary inside your script. Unity doesn’t serialize dictionaries, so you have to initialize it yourself.

public List<AudioClip> audioClipList;
     public Dictionary<string, AudioClip> audioClipDic;
 
     void Start()
     {
         audioClipDic = new Dictionary<string, AudioClip>();
         foreach (AudioClip audioClip in audioClipList)
         {
             Debug.Log(audioClip.name);
             audioClipDic.Add(audioClip.name, audioClip);
         }
     }

Thank you! Now it's working correctly!