Skip to content

Instantly share code, notes, and snippets.

@thatalextaylor
Last active October 25, 2024 12:24
Show Gist options
  • Save thatalextaylor/11408bf81bd330af2bb8062f1a2a1830 to your computer and use it in GitHub Desktop.
Save thatalextaylor/11408bf81bd330af2bb8062f1a2a1830 to your computer and use it in GitHub Desktop.
Play a random Unity AudioClip without playing the same one twice in a row
using UnityEngine;
//Play a random Unity AudioClip without playing the same one twice in a row. Useful for adding variety for otherwise repetitive sounds.
public class RandomAudioClipPlayer
{
private readonly AudioClip[] clips;
private readonly AudioSource audioSource;
private AudioClip lastClip;
//`clips` is the list of sounds to play from
//`audioSource` manages the sound playback
public RandomAudioClipPlayer(AudioClip[] clips, AudioSource audioSource)
{
this.clips = clips;
this.audioSource = audioSource;
lastClip = null;
}
//Play a sound at full volume
public void Play()
{
Play(1.0f);
}
//Play a sound at a specified volume
public void Play(float volume)
{
if (clips == null || clips.Length == 0)
return;
if (clips.Length == 1)
{
audioSource.PlayOneShot(clips[0], volume);
return;
}
AudioClip nextClip;
do
{
nextClip = clips[Random.Range(0, clips.Length)];
} while (nextClip == lastClip);
audioSource.PlayOneShot(nextClip, volume);
lastClip = nextClip;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment