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!

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.

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) {
        ...
   }

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.