Random audio clips from array on prefab crash
I have a prefab character that spawns using a UI button. I'd like to make them say a few different audio clip phrases at a random interval. I did some research on playing clips randomly, which I THINK I have coded correctly, but I have a feeling I'm doing something wrong in accessing my Audiosource. I keep getting crashes when I hit play, hence my attempt at null-checking.
For a little more info, this is a VR project. I had thought it the crash could be a VR issue since accessing the Vive seems to be buggy to me, but the project runs fine if I deactivate this audio script & the audiosrource.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Audio_Sue : MonoBehaviour
{
private AudioSource _audioSource;
[SerializeField]
private AudioClip[] _voiceClips;
private AudioClip _voicePlay;
void Start()
{
_audioSource = GetComponent<AudioSource>();
StartCoroutine("_playRandom");
if (_audioSource == null)
{
Debug.LogError("The AudioSource is Null");
}
}
IEnumerator _playRandom()
{
if (_audioSource != null)
{
int index = Random.Range(0, _voiceClips.Length);
_voicePlay = _voiceClips[index];
_audioSource.clip = _voicePlay;
_audioSource.Play();
}
yield return new WaitForSeconds(Random.Range(5.0f, 15.0f));
}
}
Your answer
Follow this Question
Related Questions
How to get random numbers for prefab objects in scene? 0 Answers
How to spawn a prefab every 5 second randomly between a set range? 0 Answers
How to change the enum value of an instance of a prefab being clicked 0 Answers
Argument Exception: GetComponentFastPath? built .exe of the game crashes! 3 Answers