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*.transform.position));*
-
if (!AICarArray[iIndex].active)* -
{*
_ AICarArray[iIndex].transform.position.x = SpawnerArray*.transform.position.x; // Set car pos to spawner pos*_
_ AICarArray[iIndex].transform.position.y = SpawnerArray*.transform.position.y + 1;
AICarArray[iIndex].transform.position.z = SpawnerArray.transform.position.z;
AICarArray[iIndex].transform.rotation = SpawnerArray.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.
– POLYGAMePerhaps you're seeing an infinite loop? This seems like it could get messy if most or all of the AICarArray is already active.
– rutteris this c#? if so your function declaration is wrong as you haven't specified a return type, consider void instead.
– Louis_WatsonOnly thing I can see is that maybe you got into that loop before you managed to set any AICarArray[iIndex].active Try performing this in a Coroutine waiting a frame or two between iterations.
– smoggachIt's JS. Got it sorted. Cheers guys :)
– POLYGAMe