字典<string,audiosource =“”>。添加()发生错误,因为直接初始化

时间:2017-11-04 04:23:23

标签: c# dictionary unity3d nullreferenceexception audio-source

all。我是c#和unity的初学者。我想用字典创建一个音频管理器。但是它出现了一个带有自爆代码的错误“NullReferenceException”。

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);
    }
}

这样改变之后就可以了。

{{1}}

我很困惑为什么我不能直接初始化字典,有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

我无法使用2017.1.1f1编辑器测试重现上述行为。我在Assets / Resources / test.mp3文件中插入了mp3文件。然后我用Test脚本创建了一个空的GameObject:

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

public class Test : MonoBehaviour {

public Dictionary<string, AudioSource> AudioDictionary = new Dictionary<string, AudioSource>() ;
private List<AudioSource> resAudioSource = new List<AudioSource>();
private const string ResourcePath = "Audio/";

public static Test instance;

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);
    }
}
}

在for循环中插入断点时,我可以看到AudioDictionary不是null,并且test.mp3被添加到AudioDictionary中。