- Home /
trying to use while that have 2 random range inside to get a any possible numbers that it will create a num
float num1=0, num2=0;
for(int i=0; i<=1; i++)
{
num1 = Random.Range(0, 9.6f);
num2 = Random.Range(0, 9.6f);
while (num1 + num2 != 9.6)
{
num1 = Random.Range(0f, 9.6f);
num2 = Random.Range(0f, 9.6f);
}
sorry if this is a noob question i just started making games(2D)
the error is that every time i run the script unity crash(kinda it just dont anything and dont respond windows not saying its not responding )
you're stuck in an infinite loop because the chance the sum of your random numbers is 9.6 is rather not existent.
As @hexagonius says you are in a (close to) infinite loop, there are thousands of possible floating point numbers between 0 and 9.6.
How about just randomise one and calculate the second. It will be the same random distribution (if my maths serves).
num1 = Random.Range(0.0f, 9.6f);
num2 = 9.6f - num1;
Actually there are pretty much a billion possible floating point numbers between 0 and 1 (specifically 2^30 == 1073741824). Your solution is of course correct and the right way to approach this.
Answer by losingisfun · Mar 22, 2018 at 04:26 AM
I highly recommend changing this.
From your code, I'm guessing you want two numbers, and for both of them to equal 9.6f? If that's the case, you should try doing something a little less verbose like:
float num1 = Random.Range (0f, 9.6f);
float num2 = 9.6f - num1;
which will achieve the exact same thing, but with possibly a thousand less operations.
Your answer
