Esla Baeny
Esla Baeny

Reputation: 83

Second Coroutine isn't working Unity

I am making 2D game and want to cause delay of about 3 sec after player's all lives ran out. I tried to implement Coroutine method before the scene start all over again but it doesn't work. I have already implemented Coroutine method for each time my player falls of a cliff and respawn back to its position. And it works like a charm.

public void Respawner()
{
    StartCoroutine("RespawnCoroutine");
}

// Coroutine  Delay of 2 sec for each time player Respawn
public IEnumerator RespawnCoroutine()
{
    classobj.gameObject.SetActive(false);   
    yield return new WaitForSeconds(respawnDelaySec);
    classobj.transform.position = classobj.respawnPoint;
    classobj.gameObject.SetActive(true);             
}

public void ReduceLives()
{
    if (lives <= 3 && lives >= 2)
    {
        lives--;
        live_text.text = "Remaining Live " + lives;
    }
    else 
    {
        StartCoroutine("RestartScene1");
    }  
}

public IEnumerable RestartScene1()
{
    yield return new WaitForSeconds(RestartSceneDelaySec);
    SceneManager.LoadScene("demo2");
}

here is no error on console window but SceneManager.LoadScene("demo2"); is never called and the player is respawning each time after i die and after 1 life remaining

Upvotes: 0

Views: 654

Answers (2)

Shweta
Shweta

Reputation: 267

The issue with your second coroutine is..

You have mistakenly used "IEnumerable" instead "IEnumerator", make it change to "IEnumerator" and it will work..

Upvotes: 3

Mohammed Noureldin
Mohammed Noureldin

Reputation: 16976

You should not call SceneManager.LoadScene("demo2"); after StartCoroutine("RestartScene1");.

StartCoroutine("RestartScene1"); this code you can say is an asynchronous code. It is called, and the execution of program keeps going forward (the execution does not await here). You should call the code you want to delay inside that Coroutine after yielding.

Small exampel:

public void SomeFunction()
{
    StartCoroutine("RestartScene1");
    // The code here will **not** be delayed
}

public IEnumerable RestartScene1()
{
    yield return new WaitForSeconds(RestartSceneDelaySec);
    // The code here will be delayed
}

Upvotes: 0

Related Questions