- Home /
How to select a random audioclip to be played in multiple places
I'm using a random array to select an audio clip, and need to send whichever clip is selected to multiple parts of my code simultaneously, including Coroutines. I'm using the Coroutines so i can use the yield return new WaitForSeconds command.
My problem is that, the way it's written now, the random sound will be selected separately in each piece of code, so both sources won't necessarily be playing the same thing. Is there a way i can trigger an audioclip to be randomly selected on GetButtonDown, which can then be somehow referenced by both the Coroutine and the GetButtonDown? I apologise in advance if this has an easy solution that i've overlooked, or has been answered elsewhere; i'm very new to C#/any code at all, and have been squinting and scratching my head over this for a few hours now.
The code looks something like this (i've stripped out anything that seemed irrelevant):
public AudioClip[] SoundEffect;
void Update () {
if (Input.GetButtonDown ("Fire1")){
AudioSource.PlayClipAtPoint(SoundEffect [Random.Range (0, SoundEffect.Length)], transform.position);
StartCoroutine( PlayElsewhere() );
}
}
private IEnumerator PlayElsewhere(){
yield return new WaitForSeconds (5);
AudioSource.PlayClipAtPoint (SoundEffect [Random.Range (0, SoundEffect.Length)], transform.Elsewhere);//i know transform.elsewhere probably doesn't exist, it's just a stand-in
Answer by Vandarthul · Dec 10, 2014 at 01:45 PM
public AudioClip[] SoundEffect;
private AudioClip randomlySelectedAudio; // Add this line.
void Update () {
if (Input.GetButtonDown ("Fire1")){
randomlySelectedAudio = SoundEffect[Random.Range(0, SoundEffect.Length]; //Add this line
AudioSource.PlayClipAtPoint(randomlySelectedAudio, transform.position); //Change this line accordingly
StartCoroutine( PlayElsewhere() );
}
}
private IEnumerator PlayElsewhere(){
yield return new WaitForSeconds (5);
AudioSource.PlayClipAtPoint (randomlySelectedAudio, transform.Elsewhere);//Change this line accordingly
I've modified your code for basically when Clicking to "Fire1" button, it will select a random AudioClip and play it, also it will play the same audio on StartCoroutine function. So I've added a variable that will hold the randomly selected audio clip whenever player clicks "Fire1" button and assigned it to the places where you want to play audio(in "Update" and "PlayElsewhere")
Looks like that did it, thank you! I was almost there at one point, but didn't have the private AudioClip randomlySelectedAudio line. Cheers!
Your answer
![](https://koobas.hobune.stream/wayback/20220613173647im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Fade, Then Stop all other audiosources attached to gameobject? 1 Answer
How can I save and load a Coroutine state ? 0 Answers
StopCoroutine Does Nothing 1 Answer