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.

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.

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;
     }