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