transform.childCount question

This is probably very easy to solve, but I’m stuck right now. I’m trying to make 1 mole spawn to a hole. I have this code below where if the childcount is 0, it should spawn 1 mole, after instantiating the mole, it’ll be assigned as a child of the hole. But it just keeps on spawning, I want it to stop after spawning 1 and wait for it to disappear before spawning a new one… am I using the transform.childCount wrong?

void Update(){

		if (transform.childCount == 0) {

			Invoke ("Spawn", Random.Range (spawnMin, spawnMax));

		}

		Debug.Log (transform.childCount);

	}
	
	void Spawn(){
		
		//Instantiate mole in the hole
		GameObject gMole = (GameObject)Instantiate(mole, transform.position, Quaternion.identity);
		gMole.transform.parent = transform;
		
	}

In your case instantiating takes time(i.e. invoking spawn) it is called until the object is spawned and child count is not 0. You’ll have to check it manually if spawn is called or not.

Another solution is to use a Coroutine as your spawner…

void Start()
{
  StartCoroutine(Spawner());
}

IEnumerator Spawner()
{
  while (true)
  {
     if (transform.Count == 0)
     {
       // wait a bit - this is what Invoke was doing
       yield return WaitForSeconds(Random.Range(spawnMin, spawnMax));

       // your original Spawn method, without the CancelInvoke
       Spawn();  
     }

     // all done for this frame
     yield return null;
  }
}