Never repeat last random audioclip

The code below is merely a snippet of the larger script, I’m curious if there is a way to not repeat the last audioclip. As I’d like the footstep audio to be randomised yet not having you hear the same clip again.

Any help would be greatly appreciated!

var sounds : AudioClip[]; 

function Update()
{
	if(grassTimer == 0)
	{
    	audio.clip = sounds [Random.Range(0,sounds.length)];
    	audio.Play();
	}
}

I think taxvi has misunderstood your question. You want to select a random sound to play each time, but not use the same one twice, correct?

The problem is, as I’m sure you’re aware, that you’re selecting from a list of all your sounds, including the one that was just played. What you want to do is select from a list of all sounds except the one that was just played. You could do this by selecting a random sound, checking if it is the one you just played, and if so selecting another, but this is bad practice as it has a small chance of locking up your program.

If you were using C#, I’d tell you to use a library called Linq for this, which allows all sorts of useful array operations, including one that can filter out array elements.

Since you’re using Javascript (and I heavily recommend you switch to C# when you can. Javascript may look easier, but it hides a lot of the complexity, which can make problems occur more easily), you can’t do this, but you can make your own filter function, somewhat like this:

function FilterCurrentClip()
{
     var rtrn : AudioClip[] = new AudioClip[sounds.Length - 1];
     var j : int = 0;
     for(var i : int = 0; i < sounds.Length; i++)
     {
         if(sounds *!= audio.clip)*

{
rtrn[j] = sounds*;*
j ++;
}
}
return rtrn;
}
This takes the existing array, and creates a new one from the values, skipping the element that you don’t want to use.
Now, when you want to set the new clip, you can do this:
var filteredSounds = FilterCurrentClip();
audio.clip = filteredSounds[Random.Range(0,filteredSounds.Length)];
This is quite a slow operation, and C#'s Linq would be a lot faster, but it should work (as long as your sounds array always contains the value of audio.clip, otherwise it will break).

Contributed to a similar question over the weekend.

No-repeat

Several methods.