Random. Range () returns the same number. (unity/c#)

Why does Random.Range () return the same number? Each time it returns 0.

Instantiate(Object[Random.Range(0, 1)], new Vector2(0, 0), Quaternion.identity);  
 2
Author: Nikita, 2020-11-07

2 answers

To get random zeros and ones, call:

Random.Range(0, 2) // integers in range [0, 2)

In the integer overload, Random. Range max is excluded:

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

Description:
Return a random integer number between min [inclusive] and max [exclusive]

Note max is exclusive. Random.Range(0, 10) can return a value between 0 and 9. Return min if max equals min.

Documentation

Description:
Returns a random integer between min [inclusive] and max [exclusive]

Attention: max is not enabled. Random.Range(0, 10) can return values from 0 to 9. Returns min if max is min.

So, you need Random.Range(0, 2)


The overload for real numbers, in contrast, includes both ends of the interval.

 3
Author: vp_arth, 2020-11-07 20:00:28

I will add, if you need from 0.5 f to 4, then here is an example.

Random.Range(.05f,4);
 1
Author: AC Studio, 2020-11-10 19:09:43