- Home /
Why would this while loop crash Unity?
I have the following code. It runs fine when I don't put it inside a while loop, but I need to as I need to try spawning another car if the one attempted is active already. I can't see anywhere that this would cause an infinite loop...
It's being called in OnTriggerEnter, not within update.
function SpawnCar()
{
while (!bCarSpawned)
{
for (var i = 0; i < iRandom; ++i)
{
iIndex = Random.Range(0, AICarArray.Length);
iRandomDir = Random.Range(1, 3);
//print(Vector3.Distance(transform.position, SpawnerArray[i].transform.position));
if (!AICarArray[iIndex].active)
{
AICarArray[iIndex].transform.position.x = SpawnerArray[i].transform.position.x; // Set car pos to spawner pos
AICarArray[iIndex].transform.position.y = SpawnerArray[i].transform.position.y + 1;
AICarArray[iIndex].transform.position.z = SpawnerArray[i].transform.position.z;
AICarArray[iIndex].transform.rotation = SpawnerArray[i].transform.rotation;
if (iRandomDir == 1)
{
AICarArray[iIndex].transform.tag = "AI_North";
AICarArray[iIndex].transform.localEulerAngles.y -= 180;
AICarArray[iIndex].transform.position.x += 2; // Put on right side of the road
//AICarArray[iIndex].rigidbody.velocity = transform.forward * -fInitialSpeedBoost; // Give initial boost
}
else
{
AICarArray[iIndex].transform.tag = "AI_South";
AICarArray[iIndex].transform.position.x += -2; // Put on left side of road
//AICarArray[iIndex].rigidbody.velocity = transform.forward * fInitialSpeedBoost; // Give initial boost
}
AICarArray[iIndex].SetActive(true);
bCarSpawned = true;
}
}
}
}
I don't know why the loop is crashing Unity but I've put the code inside Update and used a bool to trigger it, so it's working. Still be interested to know why it wasn't working, though.
Perhaps you're seeing an infinite loop? This seems like it could get messy if most or all of the AICarArray is already active.
is this c#? if so your function declaration is wrong as you haven't specified a return type, consider void ins$$anonymous$$d.
Only thing I can see is that maybe you got into that loop before you managed to set any AICarArray[iIndex].active
Try perfor$$anonymous$$g this in a Coroutine waiting a frame or two between iterations.
Answer by Kiwasi · Sep 19, 2014 at 02:28 AM
Unity is not crashing. Unity is running like crazy carrying out your infinite loop. Line 34 will never trigger if all of the AICarArray items are already active.
A better solution would be to use a for loop to iterate through the entire collection looking for an inactive object. If none is found then a new one should be created or an error thrown.
Your answer
Follow this Question
Related Questions
wierd infinite while loop 1 Answer
Why does Unity crash ? 1 Answer
Why does while make Unity crash? 1 Answer
Unity 4 Build not working on iOS 5 1 Answer
Massive memory usage during compile time 0 Answers