Home c# Random.Range in Unity 5

Random.Range in Unity 5

Author

Date

Category

The Random.Range () method with an interval from 0 to 1 for some reason does not work for me at all.

Here is the code, and below is the output:

for (int i = 0; i & lt; 100; i ++)
{
  Debug.Log (Random.Range (0, 1));
}

Result of code execution


Answer 1, authority 100%

The Random.Range method has 2 options: float Random.Range (float min, float max) and int Random.Range (int min, int max) . In your case, you are passing 2 int ‘s, so an overload that returns int is used. Since Random.Range returns numbers from [min, max) , the only integer it can return is 0. To return real numbers from [ 0, 1) , you need to pass to the float ‘s method:

for (int i = 0; i & lt; 100; i ++)
{
  Debug.Log (Random.Range (0f, 1f));
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions