How to generate a random number inside Unity?

What is the best way to generate a random number inside Unity? Is there an elegant way to directly retrieve a random GameObject from a list generated with `GameObject.FindGameObjectsWithTag ("myObject");`

@Ricardo gave an excellent solution, but I'd like to add one more point that is specific to game developers.

Pseudo random numbers may be too random for your needs. If you are determining how much damage a given hit does, your players may be frustrated by dealing very low damage 7 turns in a row. This is a perfectly normal part of random numbers but players may not see it that way. This is why a hybrid approach is often used in games.

A Shuffle Bag allows you to state the random distribution of outcomes, but control how often each outcome occurs. IE. in a true random draw, if you have a 3 in 5 chance of hitting and you swing 15 times, you could miss 15 times. You could also hit 15 times. This may not be fun in many games. With a shuffle bag, you would put 3 "hit" chips in a bag and 2 "miss" chips and draw them out one at a time. Its still random, because you don't know what order you'd pull them in; however, you avoid the chance that really bad luck could ruin your player's game.

You can even mix it up more by putting 9 hit chips in and 6 miss chips or by letting 1 in 5 hits be decided by a random number. The point is, it is way more important that your game be fun than a lesson in how probability works. If true random will seem unfair to your players, consider this alternative.

Stack Overflow question on Shuffle Bags

Excellent Source Article on Shuffle Bags

Regarding generating a random number, you have several options:

  • Unity's Random.Range. Do notice that it has slightly different behavior for the versions that receive floats, and those that receive ints.
  • .Net's own System.Random.

To obtain a list of N random items out of a collection, you could use this class. If you only need the one, then doing a Random.Range(0, collectionElements) and then indexing the collection by that value should be enough.

Do notice that while projects using Random.Range are easily run in the webplayer regression rig, projects using alternatives might not be compatible at all.

Thanks guys, Shuffle bag is what i'm looking for. I want to use it to my own game,

I have modified some code to be used in Unity.

if you wan to integrate it, here's the steps:

  1. create a javascript file name "ShuffleBag"
  2. paste this code into ShuffleBag.js

    var data = new Array(); var cursor=-1;

function add(item, num) {

var i = num || 1;
while(i--)
{
    data.push(item);    
}
cursor = data.length -1;

} function next() { var grab; var temp;

if(cursor<1) { cursor = data.length=1; return data[0]; }

grab = Mathf.Floor(Random.Range(0, cursor));
temp = data[grab];
data[grab]= temp;
data[cursor] = temp;
cursor--;
print(temp);
return temp;

}

  1. drag and drop into your gameobject you want to use this function.
  2. In your main script say it Player.js, add this code :

    var shuffle : ShuffleBag;

  3. drag your ShuffleBag in editor of your gameobject, and drop it to Player.js into script slot. (make sure you have completed step 4 correctly, unless slot for ShuffleBag won't available.

That's it.

To implement this :

shuffle.add(0,1); shuffle.add(1,3);

print(shuffle.next()); // will have chance print '0' for 25% and '1' for 75%.

What helmi meant was this code:

ShuffleBag.js

    var data = new Array(); 
    var cursor=-1;

    function add(item, num : int) {
        var i = num || 1;
        while(i--)
        {
            data.push(item);    
        }
        cursor = data.length -1;
    } 

    function next() { 
        var grab; 
        var temp;
        if(cursor<1) { 
            cursor = data.length-1; 
            return data[0]; 
        }
        grab = Random.Range(0, cursor+1);
        temp = data[grab];
        data[grab]= data[cursor];
        data[cursor] = temp;
        cursor--;
        return temp;
    }

You don't need the MathF.Floor function as Random.Range with 0 and cursor+1 as arguments will mean the Random.Range(int, int) function, which the first int is inclusive and the second one exclusive, thus the +1 for cursor. Notice the changes when assigning the temp variable, which was the main problem with helmi's code.

:)

i would prefer using Random class from system, than the unity random class

because it gives varitey of numbers and rarely repeating (even without seed) since it is seeded by system time by default!! Random Class

I am working on a library to generate pseudo random numbers in Unity. May be you are interested in use it/contribute to it:

code is OPEN and is here:

It contains also a shuffle bag

Feel free to contribute

Regards

if use c#,can use linq like:

GameObject.FindGameObjectsWithTag ("myObject").OrderBy(x => Guid.NewGuid())

to get a random sort list