Coroutine couldn't be started because the game object 'Scene Loader' is inactive

1.1k Views Asked by At

I have already searched in the Internet, also this link, and this link but didn't find the specific problem I have now.

I have a main scene with 2 buttons, where each button should open other scene (button 1 => scene 1, button 2 = > scene 2) and in each of these scenes I have a back button that should go back to the main scene.

I manage to do that successfully but when I use a Coroutine so I can have a delay of 2 seconds while loading the next scene, I get the following error when I click "Back to main scene" button:

Coroutine couldn't be started because the the game object 'Scene Loader' is inactive!

Here is my code:

public class SceneLoader : MonoBehaviour {

    private bool check = true;

    public void LoadNextScene(int numberOfScene)
    {  
        StartCoroutine(LoadAfterSeconds(numberOfScene));    
    }

    private IEnumerator LoadAfterSeconds(int numberOfScene)
    {
        while (check)
        {
            yield return new WaitForSeconds(2f);

            SceneManager.LoadScene(numberOfScene);
        }

    }

} 

When I am in the main screen and I click on the button 1 or 2 to go to the other scenes it's working as intended after 2 seconds, but when I click "Back to main scene" it doesn't do anything and I get the error that the game object 'Scene Loader' is inactive!

I know I could use Invoke() but I would like to understand what I am doing wrong.

Any help is appreciated.

Thank you.

0

There are 0 best solutions below