all.I 是 c# 和 unity 的初学者。我想用字典做一个音频管理器。但是它发生了错误“NullReferenceException”和自爆代码。
public Dictionary<string, AudioSource> AudioDictionary = new Dictionary<string, AudioSource>() ;
private List<AudioSource> resAudioSource = new List<AudioSource>();
private const string ResourcePath = "Audio/";
private void Awake()
{
#region instance
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
#endregion
AudioClip[] resAudio = Resources.LoadAll<AudioClip>(ResourcePath);
AudioSource temp;
for (int audioNum = 0; audioNum < resAudio.Length; audioNum++)
{
temp = gameObject.AddComponent<AudioSource>();
Debug.Log(resAudio[audioNum].name);
AudioDictionary.Add(resAudio[audioNum].name, temp);
}
}
像这样更改后就可以了。
public Dictionary<string, AudioSource> AudioDictionary;
private List<AudioSource> resAudioSource = new List<AudioSource>();
private const string ResourcePath = "Audio/";
private void Awake()
{
#region instance
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
#endregion
AudioDictionary = new Dictionary<string, AudioSource>();//the change
AudioClip[] resAudio = Resources.LoadAll<AudioClip>(ResourcePath);
AudioSource temp;
for (int audioNum = 0; audioNum < resAudio.Length; audioNum++)
{
temp = gameObject.AddComponent<AudioSource>();
Debug.Log(resAudio[audioNum].name);
AudioDictionary.Add(resAudio[audioNum].name, temp);
}
}
我很困惑为什么我不能直接初始化字典,任何人都可以解释一下吗?