Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Problem with using Random.

Discussion in 'Getting Started' started by Foggy-Noggin, Mar 20, 2016.

  1. Foggy-Noggin

    Foggy-Noggin

    Joined:
    Mar 6, 2016
    Posts:
    51
    I'm procedurally building my background scene from elements. I use;

    Code (csharp):
    1.  int rnd = Random.Range(0,4);
    rnd never returns 4. I've have the same line 24 times in a single function using different upper ranges, and tested extensively, each value never returns the upper range. The Documentation explicitly states both min and max range are inclusive. WTF?
     
  2. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    836
    On this page in the docs, it looks like the float overloaded version of the function is inclusive, while the integer version is exclusive.

    For the inquisitive:

    Code (csharp):
    1.  
    2.     void Start () {
    3.         int max = 0;
    4.  
    5.         for (int i = 0; i < 10000; i++)
    6.         {
    7.             max = Mathf.Max(Random.Range(0, 4), max);
    8.         }
    9.  
    10.         Debug.Log(max);
    11.     }
    ...which returns 3.
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,840
    Yep. All working as designed and documented.
     
  4. Foggy-Noggin

    Foggy-Noggin

    Joined:
    Mar 6, 2016
    Posts:
    51
    Caught not reading all the docs and taking the first answer I found. My interim solution was increment the upper range so I'm ok with what I have. So I'll walk away for now with some new understandings and a bit humble...

    Thanks