Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
28
Question by Thomas · Nov 09, 2009 at 02:18 PM · random

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

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

7 Replies

· Add your reply
  • Sort: 
avatar image
44
Best Answer

Answer by Ricardo · Nov 09, 2009 at 02:44 PM

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.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AngryAnt ♦♦ · Jan 14, 2010 at 09:27 AM 0
Share

Added notice about the webplayer regression rig.

avatar image Ricardo · Jan 14, 2010 at 07:18 PM 0
Share

I like wiki editing. But it can be overused.

avatar image Waz · Jun 22, 2011 at 12:10 AM 0
Share

The regression rig would be pretty broken if it did not have a deter$$anonymous$$istic 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.

avatar image
47

Answer by Michael La Voie · Nov 17, 2009 at 01:47 AM

@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

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ricardo · Nov 17, 2009 at 02:43 PM 4
Share

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.

avatar image Lipis · Mar 25, 2010 at 06:32 PM 0
Share

@$$anonymous$$ichael Wish I could give you one more point for StackOverflow link :)

avatar image Cyclops · May 01, 2010 at 02:54 PM 0
Share

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

avatar image Rennat · Dec 03, 2010 at 09:03 AM 0
Share
  • good answer with extra material links :)

avatar image
2

Answer by helmi · Dec 10, 2010 at 07:22 AM

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:

  • create a javascript file name "ShuffleBag"
  • 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;
    

    }

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

    var shuffle : ShuffleBag;

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

    Comment
    Add comment · Show 1 · Share
    10 |3000 characters needed characters left characters exceeded
    ▼
    • Viewable by all users
    • Viewable by moderators
    • Viewable by moderators and the original poster
    • Advanced visibility
    Viewable by all users
    avatar image joeyrubio · Feb 23, 2011 at 08:40 PM 0
    Share

    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.

    avatar image
    2

    Answer by joeyrubio · Feb 23, 2011 at 08:44 PM

    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&lt;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.

    :)

    Comment
    Add comment · Share
    10 |3000 characters needed characters left characters exceeded
    ▼
    • Viewable by all users
    • Viewable by moderators
    • Viewable by moderators and the original poster
    • Advanced visibility
    Viewable by all users
    avatar image
    1

    Answer by flamy · Dec 08, 2011 at 08:49 AM

    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

    Comment
    Add comment · Share
    10 |3000 characters needed characters left characters exceeded
    ▼
    • Viewable by all users
    • Viewable by moderators
    • Viewable by moderators and the original poster
    • Advanced visibility
    Viewable by all users
    • 1
    • 2
    • ›

    Your answer

    Hint: You can notify a user about this post by typing @username

    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

    Answers Answers and Comments

    4 People are following this question.

    avatar image avatar image avatar image avatar image

    Related Questions

    The name 'Joystick' does not denote a valid type ('not found') 2 Answers

    Random textures... 1 Answer

    Random attack animations in java. 1 Answer

    Adding GUI to this 1 Answer

    Choosing a random object with a certain tag 1 Answer


    Enterprise
    Social Q&A

    Social
    Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

    Footer

    • Purchase
      • Products
      • Subscription
      • Asset Store
      • Unity Gear
      • Resellers
    • Education
      • Students
      • Educators
      • Certification
      • Learn
      • Center of Excellence
    • Download
      • Unity
      • Beta Program
    • Unity Labs
      • Labs
      • Publications
    • Resources
      • Learn platform
      • Community
      • Documentation
      • Unity QA
      • FAQ
      • Services Status
      • Connect
    • About Unity
      • About Us
      • Blog
      • Events
      • Careers
      • Contact
      • Press
      • Partners
      • Affiliates
      • Security
    Copyright © 2020 Unity Technologies
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell My Personal Information
    • Cookies Settings
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    • Anonymous
    • Sign in
    • Create
    • Ask a question
    • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Explore
    • Topics
    • Questions
    • Users
    • Badges