Coroutine couldn't be started because the game object 'Scene Loader' is inactive
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 {
>
> public void LoadNextScene(int numberOfScene)
> {
> StartCoroutine(LoadAfterSeconds(numberOfScene));
>
> }
>
> private IEnumerator LoadAfterSeconds(int numberOfScene)
> {
> 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.
If you're saying that you don't understand how it's come to be inactive, I would suggest adding an OnDisable function with logging. That should shed some light on how/when it's being turned off.
Odds are, in the second scene you have the instance of this class disabled. Also what is the point of the loop? In any case it will run once completly and the second time till the first yield statment, after that the scene will get destroyed thus the coroutine will stop.
Thank you for your reply @PizzaPie Indeed I know that loop "while(check)" is not used at all, it was there when I was trying something and I accidentally forgot to remove it. How can I keep it persist so the scene won't get destroyed (and coroutine won't stop) and being able to move between scenes?
It doesn't make sence to make the object persistent, it will perplex things, and you don't need it.
You need a GameObject in each Scene with the SceneLoader component on it. Then assign in each button's onClick Event in the Object field the GameObject with SceneLoader script (make sure you find it in the Scene tab of the Object assigner or drag and drop the GameObject that resides in active Scene) and assign the other two fields. $$anonymous$$ake sure the GameObject with LoadScene script is active in all scenes.
Answer by PizzaPie · Nov 26, 2018 at 03:24 PM
Probably you assign the prefab(asset) in onClick event and not the active instance of it you should have in the scene.
I suggest visiting Learn section and go through, at least, the basic tutorials, before trying moving further.
Yep, that was the problem. Thank you PizzaPie! Write this as answer so I can upvote it :) Να'σε καλα!!