2017-02-19 80 views
0

我遇到了單元中的聲音問題。這是我的代碼:NullReferenceException:未將對象引用設置爲對象的實例 - UNITY SOUNDS

[RequireComponent(typeof(AudioSource))] 

公共類SoundManager類:MonoBehaviour { 公共靜態SoundManager類中的實例;

private AudioSource source; 
public Dictionary<SOUND_TYPE,AudioClip> sounds; 
public enum SOUND_TYPE 
{ 
    DEATCH, 
    CATCHED 
} 

// Use this for initialization 
void Start() 
{ 
    source = GetComponent<AudioSource>(); 

    loadSounds(); 
} 

// Update is called once per frame 
void Update() 
{ 
} 

public void playSound(SOUND_TYPE type) 
{ 
    source.clip = sounds[type]; 
    source.Play(); 
} 

public void loadSounds() 
{ 
    //loading sounds 
    sounds.Add(SOUND_TYPE.DEATCH, Resources.Load<AudioClip>("Sounds/AccelerationLow")); 
} 

}

,我必須在線路的誤差source.Add()

Error: NullReferenceException: Object reference not set to an instance of an object

我不知道發生了什麼,我該如何修復它。

回答

1

你忘了sounds構造:

public Dictionary<SOUND_TYPE,AudioClip> sounds = new Dictionary<SOUND_TYPE,AudioClip>(); 
0

這意味着public Dictionary<SOUND_TYPE,AudioClip> sounds未初始化或已空的初始化值。要初始化這個字典,在start方法中創建一個構造函數或初始化這個字典,然後在此處初始化源代碼。

要初始化一個空的字典使用:

Dictionary<SOUND_TYPE,AudioClip> sounds = new Dictionary<SOUND_TYPE,AudioClip>();

void Start() 
{ 
    source = GetComponent<AudioSource>(); 
    sounds = new Dictionary<SOUND_TYPE,AudioClip>();` 
    loadSounds(); 
} 

public void loadSounds() 
{ 
    Start() 
    //loading sounds 
    sounds.Add(SOUND_TYPE.DEATCH, Resources.Load<AudioClip>("Sounds/AccelerationLow")); 

} 
相關問題