- Home /
how can i play soundclip by name?
Hello Community, i'd like to be able to play soundclips by their names, I have a script attatched to the GameObject having audiosource, one public array of clips , the elements are assigned in inspector, in the Start() method of script I'm adding elements to the Dictionary,` public Dictionary Clips;
public Dictionary<string, AudioClip> Clips;
void Start()
{
Clips = new Dictionary<string, AudioClip>();
Clips.Add("Entry", clips[0]);
Clips.Add("Reception", clips[1]);
Clips.Add("Misc", clips[2]);
}
public void playbyname(string clipname)
{
AudioClip sound = new AudioClip();
if(Clips.TryGetValue(clipname.ToString(),out sound))
{
gameObject.GetComponent<AudioSource>().PlayOneShot(sound);
}
}
when playbyname(string clipname) is called from script B such that GameObject.Find("Narrations").GetComponent().playbyname("Entry"); the line if(Clips.TryGetValue(clipname.ToString(),out sound)) throws a null reference exception, i'm not sure whether the array gets initialized before it's elements are added to the dictionary in Start() method. How do i sort it out?
Answer by Bitpocketer · Jan 05, 2016 at 05:03 PM
Allright, thank you everbody, the problem is solved, i'm not sure if it was a problem of order of execution but i just replaced the code from Start() to Awake() and replaced the code of playbyname() with only one line that is gameObject.GetComponent<AudioSource>().PlayOneShot(Clips[clipname]); i'm not sure if i was accessing the element of a dictionary in a wrongway .
Your answer
Follow this Question
Related Questions
How to spawn new object if the one before moved out of its spawn point 1 Answer
Resources.LoadAll Generates Cast exception Error 2 Answers
Animations Through Scripting Probelm 1 Answer
If two PlayerPrefs are on? 2 Answers
Sun rotation glitchy 0 Answers