0

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

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

4

1 回答 1

0

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

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 不为空,并且 test.mp3 已添加到 AudioDictionary 中。

于 2017-11-04T21:02:47.733 回答