- Home /
Question by
Abelabumba · Feb 20, 2015 at 06:03 PM ·
beginnerrandom.rangeif else
Random.Range(0f, 10f) neither <= 5.5f nor > 5.5f, why/how?
while (winner == "no")
{
bool fighterPassed = false;
bool plotPassed = false;
if (Random.Range(0f, 10f) >= 5.5f)
{
Debug.Log("higher!");
winner = "CPU";
return winner;
}
else if (Random.Range(0f, 10f) < 5.5f)
{
Debug.Log("lower!");
winner = "Player";
return winner;
}
else if (Random.Range(0f, 10f) <= targetThrowFighter)
{
Debug.Log("how can this happen wtf");
fighterPassed = true;
return winner;
}
I don't understand how the 3rd case can ever be triggered but it does quite frequently, about 20% of the time. Is there a way to see what Random.Range returned so I can see which values trigger the 3rd case? I'm sure I'm missing something obvious here.
edit: I changed it to
else
{
Debug.Log("how can this happen wtf");
fighterPassed = true;
return winner;
}
and behavior is the same / changes as expected, it goes up to 25-30% since it doesn't have to pass the extra hurdle of <= targetThrowFighter
Comment
You are generating a new random value for each condition. Generate a random number, store that in a variable, then compare against that variable. Try this C# :
float randomNumber = Random.Range( 0f, 10f );
if ( randomNumber > 5.5f )
// Do something
else if ( randomNumber < 5.5f )
// Do something else ins$$anonymous$$d
Best Answer
Answer by Jessespike · Feb 20, 2015 at 06:23 PM
You're using a new Random number for every if-else. Solution is to use one random value for the if-else statements.
float myRandomValue = Random.Range(0f, 10f);
if (myRandomValue >= 5.5f)
{
//...
}
else if (myRandomValue < 5.5f)
{
//...
}
else if (myRandomValue <= targetThrowFighter)
{
//...
}
and so on
Your answer
![](https://koobas.hobune.stream/wayback/20220613183847im_/https://answers.unity.com/themes/thub/images/avi.jpg)