MissingReferenceException when using StartCoroutine() after reloading a scene
I have a coroutine in my script that restarts whenever the player presses the button but after reloading the scene in game causes an error: "MissingReferenceException: The object of type 'PlayerCharacter' has been destroyed but you are still trying to access it."
This is the piece of code it error directs to
if (m_driftModifier == 0.0f) { if (m_modifyDrift != null) { StopCoroutine(m_modifyDrift); m_modifyDrift = null; } float _goal = 0.0f; if (m_horizontalInput[0] > 0.1f) _goal = 1.0f; else if (m_horizontalInput[0] < -0.1f) _goal = -1.0f; else _goal = 0.0f; m_modifyDrift = StartCoroutine(moveDrift(_goal, 1)); }
This error seems to only happen if i reload the scene after it has been loaded once, it works normally otherwise.
Answer by phocker · Apr 13, 2017 at 04:34 PM
Coroutines will continue to execute even after loading a new scene. You should either add a hook on the DestroyObject method to kill the Coroutine, or have a controller flag in your Coroutine that can be used to stop it on the DestroyObject method safely.
Unfortunately this doesnt seem to change anything, i added a function to stop all coroutines i had running in OnDestroy() but the error still keeps popping up
Answer by ppizarro · Oct 23, 2017 at 06:47 PM
my solution: in "onDestroy()" stop all co-routines and unsuscribe to all dependencis or actions from another class.
private void OnDestroy()
{
StopAllCoroutines();
SomeServiceClass.OnSomeAction -= OnSomeActionMethod;
}