- Home /
Unity crashes when the game starts: maybe due to a while loop
Hi! I have a problem with some scenes in my project. When I start the game Unity freezes and I have to force the quit to close Unity process (Note that this does not always happen and the game starts properly!). After many attempts I discovered that maybe the problem is a series of while loops in my C# script (in fact removing them from the code, the game seems to start always without problems). I have a vector with nine numbers in my Start() class. Than I take a random number from the vector and I save it in a new variable, and so on for eight times. But I don't want that the same number can be stored in two or more different variables, so I wrote this code that contein the while loops. I hope someone can help me fix it so it will work without crashing unity.
int[] array = { number1, number2, number3, number4, number5, number6, number7, number8, number9 };
insidearray1 = array[Random.Range(0, 8)];
for(int i = 0; i < 9; i++)
{
if (array[i] == insidearray1)
{
array[i] = 0;
break;
}
}
insidearray2 = array[Random.Range(0, 8)];
while (insidearray2 == 0)
{
insidearray2 = array[Random.Range(0, 8)];
}
for(int i2 = 0; i2 < 9; i2++)
{
if (array[i2] == insidearray2)
{
array[i2] = 0;
break;
}
}
insidearray3 = array[Random.Range(0, 8)];
while (insidearray3 == 0)
{
insidearray3 = array[Random.Range(0, 8)];
}
for(int i3 = 0; i3 < 9; i3++)
{
if (array[i3] == insidearray3)
{
array[i3] = 0;
break;
}
}
And so on... (All thi is inside the Start() class). Thanks!
Put a breakpoint inside each of the loops and step through the code to see if it's getting stuck in an infinite loop somewhere.
Answer by _MGB_ · Aug 29, 2014 at 10:50 AM
You probably want to look more closely at what Random.Range returns...
Returns a random integer number between min [inclusive] and max [**exclusive**]
I.e. Random.Range(0,8) will never return 8.
Thanks for the explanation of the function Random.Range. Now the game always seems to start without crashing unity (I've done a lot of attempts and it's always working). It seems strange but I hope that, for some reason, the problem was that. I will test a little more, and if all goes well, the best answer will be yours.
Extrapolating your code it's possible that your array becomes full of zeroes up to index 7, whereupon you will get stuck in a while loop as the random int never allows a check of the last item (index 8).
Ed: as an aside, a rather more succinct way to randomise your array (if you are able to use Linq) could be:
var mixedUp = array.OrderBy(i => Random.value).ToList();