Avoid repetitions with Random.Range

Hi Guys, how can I avoid repetitions with Random.Range? Is it also possible to have it do a shuffle mode like Wwise where no repetitions happens until all the audio clips in the array have played at least once?

Thanks!

using UnityEngine;
using System.Collections;

public class JKPlayStingerOnPlayerEntry : MonoBehaviour {

    public AudioSource stinger;
    public AudioClip[] audioClips;
    public float lowPitchRange = .95f;
    public float highPitchRange = 1.05f;
    public bool playOnlyOnce;
   
    private bool _hasPlayedOnce;
   
    void OnTriggerEnter(Collider other)
    {
        if(playOnlyOnce && _hasPlayedOnce) return;
        if(!other.CompareTag ("Player")) return;

        float randomPitch = Random.Range(lowPitchRange, highPitchRange);
        stinger.pitch = randomPitch;
        int randomIndex = Random.Range(0, audioClips.Length);
        stinger.clip = audioClips[randomIndex];
        stinger.Play ();
        _hasPlayedOnce = true;
    }
}

Have one array listing clips, another for the randomised copy. Shuffle the source array into the second array, use the last one and reduce a counter until it reaches zero. Shuffle again.

OK - that’s beyond my programming skills, I’m only a sound designer :slight_smile: I’ll try my best, thanks.

Add this to your variables:

private AudioClip[] randomClips;
private int countdown;

Then make these methods:

    void Start()
    {
        randomClips = new AudioClip[audioClips.Length];
        Shuffle();
    }

    void Shuffle()
    {
        System.Array.Copy(audioClips, randomClips, src.Length);
        System.Array.Sort(randomClips, SoundSorter);
        countDown = randomClips.Length - 1;
    }


    int SoundSorter(AudioClip a, AudioClip b)
    {
        return Random.Range(0, randomClips.Length);
    }

And to use it:

stinger.clip = randomClips[countdown];
countdown--;
if(countdown < 1) Shuffle();
// Now set the other random parameters for playback and play stinger

Semi-untested code (didn’t try with actual sound clips), but it should work :slight_smile:

Thanks - I’ll test it and if it works I’ll post it back so that everyone can use it.