- Home /
While loop freezing Unity
So maybe I'm missing something extremely nooby, but I can't figure out why this is freezing the client.. the idea is to spawn up to 20, and each time one is destroyed, spawn a new one.
public class spawnNew : MonoBehaviour {
public int CoinsCount = 20;
public GameObject Coins;
public float spawnArea = 20.0F;
void Update () {
GameObject[] countObj;
countObj = GameObject.FindGameObjectsWithTag ("Collect");
print (countObj.Length);
while (countObj.Length < CoinsCount) {
Vector3 spawnCoord = new Vector3(Random.Range(-spawnArea, spawnArea), 0, Random.Range(-spawnArea, spawnArea));
Instantiate(Coins, spawnCoord, Quaternion.identity);
}
}
}
Edit: Thank you for all the answers, I cannot upvote everyone as I'm still rather new but I appreciate it! Sometimes it's easy to get stuck in two different 'loops' and forget the core one isn't being updated =)
I switched from a while i< and had i++ at the bottom and forgot to update the countObj!
Answer by Josh707 · Feb 11, 2014 at 06:31 AM
If a loop is causing Unity to freeze it means the loop is infinite, or never reaches it's target.
You're checking if the length of the countObj array is less than CoinsCount, but the length of the array never changes after you first populate it, so it is less than CoinsCount forever.
This is exactly the problem. It looks to me like you want to do one action for every element in the array. The for loop
was designed for this purpose, or, better still, the foreach loop
was designed specifically for iterating over arrays.
Loops work by testing a condition, doing the action, and then starting again. If you never change the outcome of the condition, then your loop will never finish.
I definitely realized it was infinite, but could't see how(was probably getting too late) Thanks! =)
Answer by whydoidoit · Feb 11, 2014 at 06:29 AM
So you aren't updating your countObj every loop (though that really isn't a very good way of doing this as it's a bit over the top!)
This would be better:
var number = countObj.Length;
while(number++ < CoinsCount) {
...
}
Answer by alti · Jan 15, 2020 at 07:24 AM
you can't do a while loop in update. Throw a:
yield return null;
somewhere in there, outside of any if statements and you'll be fine. I do not even know how the compiler allowed you to freeze things. While loops are done under IENumerators, not voids.
This is completely incorrect information. You can absolutely use a while loop in update, you can use one anywhere. What you can't do is use a while loop that never ter$$anonymous$$ates without having some way for code execution to leave that loop, otherwise it will just happily continue doing calculations forever and freeze your program.