Restarting a Coroutine ignored the yield WaitForSeconds

I have an IEnumerator for a coroutine that spawn object like this

public IEnumerator spawnCoroutine;
private float spawnObstacleTimer;

void Start () {
        spawnObstacleTimer = GameObject.Find("EventSystem").GetComponent<gameManager>().spawnObstacleTimer;
        spawnCoroutine = spawnObsCoroutine(spawnObstacleTimer);
        startSpawnCoroutine();
    }

public IEnumerator spawnObsCoroutine(float timer)
    {
        while (true)
        {
            yield return new WaitForSeconds(timer);
            spawnObs();
        }
    }

public void startSpawnCoroutine()
    {
       StartCoroutine(spawnCoroutine);
    }
public void stopSpawnCoroutine()
    {
        StopCoroutine(spawnCoroutine);
    }

And I start it on the Start() which it run fine. But I’ve put a collision detection to stop this Coroutine when triggered. Again this is running fine but it’s when I call the OnCollisionExit() that restart the Coroutine with the function startSpawnCoroutine(); a new object is spawned immediatly and is ignoring the yield return new WaitForSeconds()

So how this happen? StopCouroutine should stop it all and when I restart it, it should wait for seconds before executing the spawn.

Thanks for your help

You can’t reuse the IEnumerator that is returned by a generator method. Such an IEnumerator can only be used once. You have to create a new one each time you want to start a coroutine. Also it’s better to use the Coroutine instance that is returned by StartCoroutine to stop the coroutine.

public Coroutine spawnCoroutine;
private float spawnObstacleTimer;
void Start ()
{
    spawnObstacleTimer = GameObject.Find("EventSystem").GetComponent<gameManager>().spawnObstacleTimer;
    startSpawnCoroutine();
}
public IEnumerator spawnObsCoroutine(float timer)
{
    while (true)
    {
        yield return new WaitForSeconds(timer);
        spawnObs();
    }
}
public void startSpawnCoroutine()
{
    spawnCoroutine = StartCoroutine(spawnObsCoroutine(spawnObstacleTimer));
}
public void stopSpawnCoroutine()
{
    StopCoroutine(spawnCoroutine);
}