x


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);
    }
}
more ▼

asked Jul 30 '11 at 01:29 PM

oliver-jones gravatar image

oliver-jones
2.5k 205 225 253

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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 );
    } 

}
more ▼

answered Jul 30 '11 at 01:43 PM

Joshua gravatar image

Joshua
6.4k 19 25 70

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x571
x123
x106
x42

asked: Jul 30 '11 at 01:29 PM

Seen: 1289 times

Last Updated: Jul 30 '11 at 01:44 PM