Randomly Play an audio Source

I have multiple audio sources through out my scene. I am working on a 3d audio project. Upon entering play mode I want the audio sources to be triggered randomly one after another without repeating before all sounds are played. Just to make it clear I dont want random audio clips, which I could put in an array and loop through. I want the audio sources to be triggerd from their respective position as I am working on audio spatialization.

Heya :slight_smile:

The way I’m going to do this is by having an array of the AudioSources in your scene. Each audio source will of course have its own position, and you should set their audio clips in the inspector. Next, we’re going to fill an empty list with all the AudioSources in the array. The next step is to trigger a random AudioSource from that list, remove it from the list, and repeat until the list is empty. Then we start the whole cycle over again. For simplicity, I’ll have it play a sound every second. Of course you could get the audio clip’s length and wait that amount of time if you want.
Also, don’t forget to put “using System.Collections.Generic;” in your script.

public AudioSource[] sourcesInScene; //assign these in the inspector
List <AudioSource> sourcesList;
void Start () {
    StartCoroutine (SoundsTick());
}
IEnumerator SoundsTick () { //we're using an ienumerator so we can "wait" between loops.
    while (true) {
        sourcesList = new List<AudioSource>();
        for (int x = 0; x < sourcesInScene.length; x ++) {
            sourcesList.Add(sourcesInScene[x]);
        }
        for (int z = 0; z < sourcesList.count; z ++) {
            yield return new WaitForSeconds(1f);

            int i = Random.Range(0, sourcesList.count);
            sourcesList*.Play();*

sourcesList.Remove(i);
}
}
}
There might be a few errors in this code, so instead of copying it directly, maybe just use it as a guide instead. Hope I helped :slight_smile: