Spawning does not wait.

using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour {
    bool spawn = true;
    public int time = 2;
    public GameObject enemyPrefab;
    public int i;
    public int amount;
    // Use this for initialization
    void Start () {

    }
   
    // Update is called once per frame
    void Update(){
        StartCoroutine(Timer ());
   
    }
    //time the spawner.
    IEnumerator Timer(){

        while (spawn){
            yield return new WaitForSeconds(time);
            time = Random.Range (3,6);
            amount = Random.Range (1,4);
            StartCoroutine(Spawn(amount));
           
        }
    }
    // spawn an amount of enemies.
    IEnumerator Spawn(int amount){
   
        for(i=0;i<amount;i++){
            yield return new WaitForSeconds((float)0.2);
        Instantiate(enemyPrefab,transform.position,transform.rotation);
        }
        yield return new WaitForSeconds(time);
    }
}

The problem is after the first wave of enemies being spawned it goes out of control and does not spawn them on the interval I told it to.

Since you are starting your coroutine from update, it will run it about 60 times per second - all the time. You probably want place your coroutine in “Start()”.

Coroutines run constantly on their own. Maybe put the StartCoroutine(Timer()); in your Start() function instead. It may be building up too much every frame and that’s why it’s going out of control.

Beat me to it :slight_smile: I had the same problem when I tried my first Coroutine. It crashed Unity on me every time I tried to run it and I couldn’t figure out why. lol.