- Home /
How to loop through a list of sounds if(bool)
UPDATE: I fixed the error. audioSource = GetComponent<AudioSource>()
is called in Start() but I Start() is never executed I guess. The following works:
public void PlaySound()
{
audioSource = GetComponent<AudioSource>()
PlayList();
}
QUESTION: I have the script below attached to gameobject with a audiosource. When a condition is true, I call the function PlaySound()
through another script (and when false I call StopSound()
). But this isn't working. I get the error:
NullReferenceException: Object reference not set to an instance of an object
PlayEatingSounds.PlayList () (at Assets/Scripts/PlayEatingSounds.cs:30)
At line 30: audioSource.clip = audioClips[Random.Range(0, audioClips.Count)];
The list with audioclips is definitely not empty. I have 0 clues or google results in how to tackle this, please help.
public class PlayEatingSounds : MonoBehaviour
{
public Vector2 pitchRange;
public List<AudioClip> audioClips = new List<AudioClip>();
private AudioSource audioSource;
private AudioClip audioClip;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
public void PlaySound()
{
PlayList();
}
public void StopSound()
{
CancelInvoke();
}
void PlayList()
{
audioSource.clip = audioClips[Random.Range(0, audioClips.Count)];
audioSource.pitch = Random.Range(pitchRange.x, pitchRange.y);
audioSource.Play();
Invoke("PlayList", audioSource.clip.length);
}
}
change public List<AudioClip> audioClips = new List<AudioClip>();
to public AudioClip[] audioClips;
and set it in the inspector. and change audioClips.Count
to audioClips.Length
Why does it matter if it's a array or List?
It cleaner, less memory + the real problem is probably
public List<AudioClip> audioClips = new List<AudioClip>();
making a new instance will probably overwrite everything in the editor.
Answer by Y00 · Aug 03, 2017 at 11:14 AM
if The list with audioclips is not empty, maybe audioSource is empty? Try to specify it in the inspector instead GetComponent
Your answer
Follow this Question
Related Questions
accessing the previous click object information 0 Answers
audio doesn't play on movement 0 Answers
How can i set audio mixer groups volume to be used with ui slider when 0 is lower and 80 louder ? 1 Answer
Audio Clip Playing every frame 2 Answers
Hello eveyone, i want to make a footstep sound but my code doesn't make the audio work properly 2 Answers