Instantiating prefabs with coroutine delay not working

Greetings - Currently, I have an issue where I am attempting to instantiate a prefab multiple times, with a delay between each instantiation implemented through a coroutine. The issue is that the instantiating is happening all at once, ignoring the delays implemented in the coroutine.

This is for a simple 2D space shooter where enemy waves are being spawned. Currently, it’s attempting to spawn only one wave of 10 enemies, with a delay of 5 seconds between each enemy spawn.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour {
    // Object references
    [SerializeField] GameObject enemyPrefab;

    // Game parameters
    [SerializeField] float enemyStartingXPosition = 7f;
    [SerializeField] float enemyStartingYPosition = 7f;
    [SerializeField] int enemiesPerWave = 10;

    /// <summary>
    /// Start is called on the frame when a script is enabled just before
    /// any of the Update methods is called the first time.
    /// </summary>
    void Start() {
        SpawnEnemyWave();
    }

    void SpawnEnemyWave() {
        for(int i = 0; i < enemiesPerWave; i++) {
            StartCoroutine(SpawnEnemy());
        }
    }

    IEnumerator SpawnEnemy() {
        Instantiate(enemyPrefab, new Vector3(enemyStartingXPosition + Random.Range(2f, 5f), enemyStartingYPosition + Random.Range(2f, 5f), 0), Quaternion.identity);
        yield return new WaitForSeconds(5);
    }
}

If I run the above, all 10 enemies appear on my screen right at game start, whereas I was expecting each to appear after 5 seconds due to the delay in the coroutine.

Rather than a for loop, I’ve tried wrapping the Instantiate() statement in an if loop checking for a left-mouse button click in the Update function. This enables enemies to be spawned “on-demand” and works fine. It’s only when I call Instantiate() 10x in a for loop and change to a coroutine that the delay is not happening.

Any help or insights would greatly be appreciated.

.You are starting multiple coroutines which are all running at the same time. Put your for loop in the coroutine and start it once.

Perfect! Thanks for the tip, I had tried multiple things but think I misunderstood how a coroutine truly performs. I managed to fix it per your advice.