Spawning enemies at random times, so close!


Okay so ive been trying almost all day now to get this to work and im close i can feel it!
I need the enemies to spawn at random times, delay for about a second then destroy them selves and spawn the next one, almost like a loop!

thisEnemy = Random.Range(0, 1); //random enemy
spawnDelay = Random.Range(1f,3f); //random time, from 1-3
dieTime = Random.Range(3f,6f);
nextEnemy = Random.Range(1, 1); // Follow up enemy


What i need it to do is spawn the first enemy, then spawn the second enemy after say 3 seconds but using the same delays, dietime etc. If that makes sense.

Again thanks for any help hope that was clear,

Why not just create single coroutine which will handle whole this process?

public GameObject[] enemies;
	private void Start(){
	private IEnumerator SpawnHandler(){
		float spawnDelay;
		int thisEnemy;
		GameObject cachedEnemy;
		float dieTime;
			thisEnemy = Random.Range(0, enemies.Length); //random enemy
			spawnDelay = Random.Range(1f,3f); //random time, from 1-3
			dieTime = Random.Range(3f,6f);

			yield return new WaitForSeconds(spawnDelay); //wait that time
			cachedEnemy = (GameObject)Instantiate(enemies[thisEnemy], transform.position, transform.rotation);//spawn enemy, cache him
			StartCoroutine(Kill(dieTime, cachedEnemy));
	private IEnumerator Kill(float wait, GameObject enemy){
		yield return new WaitForSeconds(wait);

Didn’t test, but should work

Invoke repeating is good for things that need a to be called on a defined frequency. For random times I would use a custom timer. You need to call the randomisation each time. Here is how I would code it. (c#)

private float nextSpawnTime

void Update (){
    if (Time.Time > nextSpawnTime){
        Spawn ();
        // Set the limits as appropriate
        nextSpawnTime += Random.Range(0,2);

void Spawn (){
    int enemyIndex = Random.Range(0, enemies.Length);
    // This line gets a reference to your new enemy
    GameObject newEnemy = (GameObject)Instantiate(enemies[enemyIndex], transform.position, transform.rotation);
    // This line calls a delayed destroy;
    Destroy (newEnemy, 2);