Camera Errors upon scene reload?

I have my dynamic camera working flawlessly when I play the game. However, if I reload the scene with a script that calls:

        Scene scene = SceneManager.GetActiveScene(); 
        SceneManager.LoadScene(scene.name);

then I get the following error for all future calls to the action cam:
“MissingReferenceException: The object of type ‘GameObject’ 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.”

Any ideas what I might have done wrong? Shooting still works perfectly, so I am baffled :slight_smile:

1 Like

I solved it, so I thought I would leave the answer up here, for anyone else that makes the same mistake!

I started to do my own thing and deviated from the code. As such I have created more events that I am subscribed to. However, I didn’t unsubsribe to any of them.

Anyways, if you are doing your own thing, make sure to add to the end of your code block:

private void OnDestroy()
{
     //Unsubscribe to your events here
     //For example:
     //SomeScript.OnEvent -= SomeScript_OnEvent;
}

Hope this helps!

2 Likes

That’s correct. Once you are to the point of switching scenes, it’s vital that all subscribers unsubscribe from static events at the very least, and preferably all events.

As a rule of thumb:
If you subscribe in Awake() or Start(), unsubscribe in OnDestroy()
If you subscribe in OnEnable() unsubscribe in OnDisable().

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms