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
Answer by flashframe · May 28, 2016 at 01:47 PM
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);
}
}
Your answer

Follow this Question
Related Questions
this script is missed up help? 1 Answer
Help with a C# script .SetActive 1 Answer
JavaScript Problem - BCE0043 - Unexpected Token Help 0 Answers
Accessing script from another object 1 Answer