Unity Random.Range when using Int, doesnt seem random at all?

by Super MegaBroBro   Last Updated November 14, 2017 17:13 PM

I have a simple script that should cycle through 4 music tracks and select the next one to be played.

      nextSong = Random.Range(0, 3);

I've run my game approx 50 times and its never been 3. It's been 0 and 2 mostly but occasionally 1.

Is this something to do with it being rounded/casted from float to int?

nextSong is declared as an Int.

Anyone know whats going on here? Surely it cannot miss track 3 more than 50 times, or was it just many consecutive "lucky" rolls for 0 and 2?

Here is all the code in case it is relevant:

void Update () {
    if (!audioSource.isPlaying)
        nextSong = Random.Range(0, 3);
        audioSource.clip = songs[nextSong];
        Debug.Log("should be playing next random track  number : " + nextSong + "called: " + songs[nextSong]);
Tags : unity c# random

Answers 1

The documentation says that you will never get 3, the max is exclusive.

public static int Range(int min, int max);


Returns a random integer number between min [inclusive] and max [exclusive] (Read Only).

Note that max is exclusive, so using Random.Range( 0, 10 ) will return values between 0 and 9. If max equals min, min will be returned.

So in your situation, you should call it with 4:

int SONG_COUNT = 4;

nextSong = Random.Range(0, SONG_COUNT);

The rest of your issue is that: 0 and 2 got lucky :)

I'm not sure there is something in Unity that would allow you to have something like that, but you could program it yourself: a "random bag".

The idea is that you put all of your "songs" in a "bag", pick one out (at random), use it but leave it out of the bag. Do this until there is only one left. Do it again, but keep the last one you've picked out in your hand, and put back all of the others back in the bag. The next time you need a song, pick it from the bag, then put back the previously one used (that you did not put back in the bag). Rinse and repeat.

The idea is that you'll use all of your songs before one can be repeated. And you keep the last one out before re-starting to use them to make sure that you'll never get the same some twice in a row.

Alexandre Vaillancourt
Alexandre Vaillancourt
November 14, 2017 16:59 PM

Related Questions

Random Sobol 3D Cell in Unity

Updated March 24, 2018 13:13 PM

Randomly changing game scenes in unity c#

Updated June 23, 2018 14:13 PM