- Home /
Issue with random.range in if clause
Hey, guys. So, I need your help with if statement and Random.Range. There is my script below:
void Update()
{
if (Random.Range(0,2) == 0)
{
Debug.Log("0");
}
else if (Random.Range(0,2) == 1)
{
Debug.Log("1");
}
else
{
Debug.Log("2");
}
}
Sometimes I get the "2" result in the console. I absolutely don't understand this, because I used all of "Random.Range" numbers (0 and 1) in my "if" and "else if" clauses. For this reason "else" clause shouldn't work, but it does! Could you tell me, why?
And the similar situation with another code:
void Update()
{
if (Random.Range(0,2) == 0)
{
Debug.Log("0");
}
else if (Random.Range(0,2) == 1)
{
Debug.Log("1");
}
else if (Random.Range(0,2) == 2)
{
Debug.Log("2");
}
else
{
Debug.Log("3");
}
}
I never get "2" result, but sometimes get "3" result that is even more strange. So, how can I check numbers correctly? I have to use "==", not ''>" or "<" in the conditions
Answer by Dragate · Jul 28, 2019 at 07:55 AM
With your code, in every if-statement you evaluate a different random number. You should store your random number into a variable and use that variable instead.
int rand = Random.Range(0,2); // Generate 0 or 1
if (rand == 0) {
Debug.Log("0");
} else if (rand == 1) {
Debug.Log("1");
} else {
Debug.Log("2"); // Will never be executed
}
Also, you should read the docs to find out that Range() with integer arguments will return an interger number in the range of [min, max). Max is exclusive. You could use the method with the float arguments and then typecast the result to an integer if you want your max to be inclusive.
Uhm, If you just want two outcomes, just do this:
if (Random.Range(0,2) == 0)
{
Debug.Log("0");
}
else
{
Debug.Log("1");
}
And everything's fine. "Random.Range(0,2)" can only return 0 or 1. So if the number is not 0 it has to be one. Of course this doesn't work if you want more than 2 outcomes in which case you have to use either a variable or a switch statement. For example:
switch(Random.Range(0,4))
{
case 0:
Debug.Log("0");
break;
case 1:
Debug.Log("1");
break;
case 2:
Debug.Log("2");
break;
case 3:
Debug.Log("3");
break;
}
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
Confused about custom GameObjects,Custom GameObject confusion 0 Answers
Get callback when assets loading or deserialization finished? 1 Answer
NEED HELP script doesn't work after reloading project 1 Answer
Multiple Cars not working 1 Answer