How to pauze the script in a while loop?

Hi people,

I need some help with my script here. It is now instanciating all the gameobjects at the same time, butI need to hold the while loop for a second before instantiating the next game object when it loops around. I tried it with a coroutine, but this does not work. I hope you can help me with this. Thanks!

	public void Sprout()														
	{
		randomSprouts = Random.Range (1, 4);									

		while (randomSprouts >= 0) 												
		{
			x = Random.Range (-1.0F, 1.0F)-spawner.localPosition.x;				
			y = Random.Range (-0.5F, 0.5F)+spawner.localPosition.y;				
			z = Random.Range (-0.20F, -0.15F)-spawner.localPosition.z;			
			Vector3 position = new Vector3(x,y,z);								
			StartCoroutine(wait());
			Instantiate (leaf, position, Quaternion.identity);					
			randomSprouts--;													
		}
	}
	IEnumerator wait()
	{
		yield return new WaitForSecondsRealtime(1);								
	}

You are not taking advantage of coroutines in your code. If you call StartCoroutine that way you’ll just start the wait function and go on with your while loop regardless what the coroutine is doing. I haven’t tested but your program will probably hang if you run it.

It should look more like the following:

    public void StartSprouting() // call this from outside
    {
        StopAllCoroutines();
        StartCoroutine(Sprout_Coroutine());
    }

    IEnumerator Sprout_Coroutine()
    {
        randomSprouts = Random.Range(1, 4);

        while (randomSprouts >= 0)
        {
            x = Random.Range(-1.0F, 1.0F) - spawner.localPosition.x;
            y = Random.Range(-0.5F, 0.5F) + spawner.localPosition.y;
            z = Random.Range(-0.20F, -0.15F) - spawner.localPosition.z;
            Vector3 position = new Vector3(x, y, z);

            yield return new WaitForSeconds(1f);

            Instantiate(leaf, position, Quaternion.identity);
            randomSprouts--;
        }
    }

Thanks a lot! This works like a charm :slight_smile: