- Home /
LoadLevel break coroutine ?
So I have a simple where i start a coroutine, which works fine. But if I reload the same level with Application.LoadLevel (Application.loadedLevel), I get the following error when I try to start the same coroutine :
MissingReferenceException: The object of type 'GameManager' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
"GameManager" if the script where the coroutine is. The script instance or its gameObject are never destroyed explicitly.
Anyone has an explanation or a solution ? Thanks in advance
Answer by hvilela · Aug 27, 2012 at 04:40 PM
The explanation is simple: All game objects are destroyed when you load a level, otherwise your levels would overlay each other. The solution is also simple: call DontDestroyOnLoad passing your GameManager object as parameter.
$$anonymous$$eep in $$anonymous$$d when you use DontDestroyOnLoad on objects that are loaded from a scene, when you reloading the same scene you end up with two objects. The old one is not destroyed and the "new" level comes with it's own instance.
That works, thanks.
But why the game was still trying to access the old gameObject or script instance and not the new one since the call to the coroutine was made in the new script instance ?
my solution: on "onDestroy()" stop all co-routines and unsuscribe to all dependencis or action from another class.
private void OnDestroy()
{
StopAllCoroutines();
SomeServiceClass.OnSomeAction -= OnSomeAction$$anonymous$$ethod;
}
Your answer
Follow this Question
Related Questions
Wait For Seconds to Load level C# 2 Answers
LoadLevel at the end of a sound ! (pb with Coroutine) 0 Answers
Coroutine Death on Scene Change 3 Answers
coroutine or yeild for OnGUI? 0 Answers
Running Coroutines Between Levels 4 Answers