- Home /
MissingReferenceException on Inspector-assigned values after reloading scene
I have a level scene where gameplay takes place. In this scene, I have a canvas.
I also have a PlayerGUI (manager object) that has Inspector-assigned references to the canvas elements it needs to enable/disable depending on the gameplay state.
I enter the scene in gameplay and press the pause button to bring up the pause UI (PlayerGUI calls the SetActive(true) method on the GameObject reference to the panel of the pause UI).
I then reload the scene using SceneManager.LoadScene, and try to open the pause UI again. This time, I'm given an exception:
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.
The exception points to this line:
PanelPauseMenu.SetActive(true);
I am almost certain this has to be a bug in Unity. When checking the Hierarchy during gameplay, PlayerGUI has a live reference to the correct element (the reference can be double clicked, and the live, correct UI element is highlighted).
Does anyone have any idea why this happens? Everything works fine the first time around, but completely fails if the level is loaded again -- it's like the references aren't updated when the level is reloaded, although they appear correct in the Inspector.
Answer by Mattyizz · Jul 29, 2016 at 11:46 AM
Found the solution:
I'm using an Event-system with delegates. Not correctly removing my delegates from the events in OnDestroy was the culprit, although this seems weird, as only one delegate was called (I added a print statement to the delegates, and only one line was ever printed), and new instances of PlayerGUI would just add their own delegates to the event as well, which should still work.
Anyway, hope it will help somebody else in the future.