x


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

more ▼

asked Nov 09 '09 at 02:18 PM

Thomas gravatar image

Thomas
378 6 8 14

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

7 answers: sort voted first

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.

more ▼

answered Nov 09 '09 at 02:44 PM

Ricardo gravatar image

Ricardo
5.2k 20 32 96

Added notice about the webplayer regression rig.

Jan 14 '10 at 09:27 AM AngryAnt ♦♦

I like wiki editing. But it can be overused.

Jan 14 '10 at 07:18 PM Ricardo

The regression rig would be pretty broken if it did not have a deterministic System.Random. I way prefer System.Random since you can have more than one random stream, which makes it easier to keep the game repeatable during development.

Jun 22 '11 at 12:10 AM Waz
(comments are locked)
10|3000 characters needed characters left

@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

more ▼

answered Nov 17 '09 at 01:47 AM

Michael La Voie gravatar image

Michael La Voie
2.3k 7 12 43

Good point. I knew the idea of Shuffle Bags, but didn't know they had a name, and it didn't occur to me to suggest them.

Nov 17 '09 at 02:43 PM Ricardo

@Michael Wish I could give you one more point for StackOverflow link :)

Mar 25 '10 at 06:32 PM Lipis

@Lipis, I just ran into this answer, so here's another +1. It's a very nice gaming tool.

May 01 '10 at 02:54 PM Cyclops

+1 good answer with extra material links :)

Dec 03 '10 at 09:03 AM Rennat
(comments are locked)
10|3000 characters needed characters left

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%.

more ▼

answered Dec 10 '10 at 07:22 AM

helmi gravatar image

helmi
49 1 1 6

I copied exactly what you put here and that didn't work. I will post another answer below with almost the exact same code but with a few changes that will make it work perfectly! This was still really helpful though, thanks.

Feb 23 '11 at 08:40 PM joeyrubio
(comments are locked)
10|3000 characters needed characters left

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.

:)

more ▼

answered Feb 23 '11 at 08:44 PM

joeyrubio gravatar image

joeyrubio
31 4 4 9

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

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

more ▼

answered Dec 08 '11 at 08:49 AM

flamy gravatar image

flamy
3.6k 5 12 38

(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:

x5273
x599

asked: Nov 09 '09 at 02:18 PM

Seen: 37832 times

Last Updated: Jan 30 at 05:39 AM