- Home /
Prevent Random.Range From Repeating Same Value
Hello,
I'm working on a music player for my game, what it does, is it randomly selects 1 out of 5 songs by using Random.Range.
The problem is that sometimes, Random.Range selects the same number it previously selected, thus playing the same song. How do I prevent Random.Range from selecting a value it previously chose?
var song1 : AudioClip;
var song2 : AudioClip;
var song3 : AudioClip;
var song4 : AudioClip;
var song5 : AudioClip;
var currentSong : AudioClip;
var randomValue : int;
function Start(){
while(true){
randomValue = Random.Range(1, 5);
if(randomValue == 1)
currentSong = song1;
else if(randomValue == 2)
currentSong = song2;
else if(randomValue == 3)
currentSong = song3;
else if(randomValue == 4)
currentSong = song4;
else if(randomValue == 5)
currentSong = song5;
audio.clip = currentSong;
audio.Play();
yield WaitForSeconds(currentSong.length + 10);
}
}
Answer by Joshua · Jul 30, 2011 at 01:43 PM
I'd use a list to keep track of used values. Also, not that Random.Range( int, int ) is [inclusive, exclusive], so you need to use (1, 6);
using System.Collections.Generic;
var songs : Audioclip; //add the songs manually in the inspector.
var usedNumbers : List.< int > = new List.< int >;
var notDone : boolean = true;
function Start()
{
while( notDone )
{
if( usedNumbers.Count >= 5 )
{
Print( "We've used all the numbers" );
notDone = false;
return;
}
var newNumber : int = Random.Range( 1 , 6 )
while( usedNumbers.Contains( newNumber ) )
{
newNumber = Random.Range( 1, 6 );
}
usedNumbers.Add( newNumber );
audio.clip = songs[ newNumber ];
audio.Play();
yield WaitForSeconds( songs[ newNumber ].length + 10 );
}
}
Your answer
Follow this Question
Related Questions
Random.range returning similar values 1 Answer
Random.value sometimes doesn't instantiate my prefab(pic included) 1 Answer
Store multiple random integers in an array? 4 Answers
[Beginner] Using Random.Range in initial game object position 1 Answer
How can i add random range to an instantiated objects rotation? 1 Answer