Search code examples
c#arraysunity-game-enginerandomindexoutofboundsexception

Array doesnt give an Out of bounds Error Message while picking a Random item C#/Unity


I have a beginner question. Why does this code not result in an error message?

public Tile[] tiles = new Tile[2];
...
SetTile(0, 0, 0, nocollide, tiles[Random.Range(0,2)]);

The Array is has two items in it but I pick a value from 0 to two, which are three items. When I make it to 0,1 it just picks the first item. But why?


Solution

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

    Description

    The reason is simple, Return a random integer number between min [inclusive] and max [exclusive] (Read Only).

    max is exclusive. Random.Range(0, 10) can return a value between 0 and 9.

    If you want to include the max value then you can use the below-overloaded method.

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

    Description

    Return a random float number between min [inclusive] and max [inclusive] (Read Only).

    max is inclusive. Random.Range(0.0f, 1.0f) can return 1.0 as the value.

    Reference: https://docs.unity3d.com/ScriptReference/Random.Range.html