MissingReferenceException: The object of type 'Animator' 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.

I have an endless runner game and my player can respawn after wathing an ad. But after the player goes to the market page, or just tries again without reviving, unity gives the error

“MissingReferenceException: The object of type ‘Animator’ 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.”. I’m using LoadScene function to restart the game or coming back from the market.

This is my code for restarting the game after death.

    public void TryAgain()
    {
        PlayerPrefs.SetInt("TotalMoney", numberOfCoins + PlayerPrefs.GetInt("TotalMoney"));
        SceneManager.LoadScene(0);
        scoreMultiplier = 1;
        numberOfBullets = 0;       
    }

And this is the one that works after the ad ends. But error says it cant find the animator in here.

    public void Revived()
    {
        moveSpeed = 10;
        PlayerManager.scoreMultiplier = 1;
        death = false;
        animator.SetTrigger("Revive");
        deathStuff.SetActive(false);
    }

For anyone looking for a less “patchy” solution, my errors had to do with not unsubscribing some callbacks in scripts that were in an observer pattern (you should do this OnDestroy), and then also some scriptable objects were referencing destroyed objects (since scriptable objects are persistent). The above solution will work in all (if not most) situations regardless.

Just set the gameObject to dont destroy on load like this:

DontDestroyOnLoad(this.gameObject);//the animator gameObject
SceneManager.LoadScene(0);

This is how unity understands:

Scene 0 go1 on RAM 0001
Scene 1 go1 on RAM 0002

Than in scene 1 you are trying to access 0001 witch is destroyed.

Ok try this:

public class Running : MonoBehaviour{

    void Start(){
        DontDestroyOnLoad(this.gameObject);
        DontDestroyOnLoad(animator);
    }
}

I wrote

        if(animator == null)
        {
            animator = GetComponentInChildren<Animator>();
        }

in the update function and it worked.