Unity3D for iOS: “MissingReference” Error After Calling Application.LoadLevel()

I got a MissingReference error recently when loading a scene for the 2nd time via Application.LoadLevel(). In other words, I had MENU scene that handled some game settings, etc. When you hit the PLAY GAME button, Unity loaded a GAMEPLAY scene. After finishing the game, the MENU scene would load again. Without quitting the game, if I hit the PLAY GAME button inside MENU again, it would once more call Application.LoadLevel() on the GAMEPLAY scene. GAMEPLAY scene loaded ok for the 2nd time but shortly after calls to certain UIToolkit objects would generate a “MissingReference” error, similar to this one:

MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.

Both scenes had a GameStructureManager script. Inside the GameStructureManager script I created some members of type GameObject inside Start() via GameObject.Find() and grabbed the script component via GetComponent() in a C# project. I also assigned Events via Delegates, a technique I learned from Prime31’s UIToolkit plugin:

    void Start() {          
       MyGameObject1 = GameObject.Find("HUD_Manager");     
       MyHUD = (HUDscript) MyGameObject1.GetComponent<HUDscript>();       

        HUDScript.onContinue += onContinueStuffHandler;         


Adding an OnDestroy() and using it to unsubscribe from events subscribed to in Start() fixed the MissingReference error in this case:

    void OnDestroy() {
       HUDscript.onContinue -= onContinueStuffHandler;     

       Destroy( MyGameObject1 );
       Destroy( MyHUD );

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s