GameObject still destroyed after reloading level.

I’m on a team that’s making a short game that consists of two scenes: the start screen, and the game itself. The start screen has a Play button that when clicked, loads the scene that contains the game. When the game ends (on a win, loss, etc.) the main menu is loaded again. If you click Play a second time however, I get the following error:
“MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.”

I don’t understand how this is possible. I thought that when you load a level, everything is restored to its initial state. Is that not the case? And if it is, why would it work the first time, but not the second time?

We never explicitly tell Unity to destroy the gameobject, so I’m assuming it’s getting destroyed (along with everything else) when we load the main menu scene, and then for some reason it isn’t getting recreated when we load the game scene the second time. The weird thing is though, when I pause the game and look at the scene, the gameobject in question is still there in the hierarchy. Does anyone know what could be causing this?


I’m guessing the script throwing the error is set to “DoNotDestroyOnLoad” so it’s reference variable isn’t being reset. Since the object is back again when the scene loads but no longer attached to the script, simply have it’s Update function check for null and do a FindObjectOfType(typeof (YourObject) ) to grab it again if it’s missing. That will grab the reference to the newly instantiated item.

I went through this in last few hours, it was driving me crazy.

Then I realized I had a few “static” references to gameobjects in the gameplay scene which survive on reloads, but of course it points to a resource that has been allocated somewhere else on reload.

Check out if you have some other gameobject holding a static references to the gameobject that is null the second time you load the scene and clean it up
(it is very common to use static refs to things in the scene inside a “singleton GameManager”, careful with that).