Search code examples
unity-game-enginereloaddestroyscene

Unity3D - Problems after reloading scene via Application.LoadLevel


I have a problem...

There are four scenes in my game: An opening scene, a scene to select players, the actual game play scene, and the game over scene.

I am running into problems when I load my actual play scene additional times

Application.LoadLevel("Let's play the game!") 

This is how I am leaving this scene:

if(GUI.Button (new Rect (x, y, w, h), "Quit", buttonStyle))
{
   Application.Quit();
   Application.LoadLevel("Opening Screen");
}

When I load my desired level a second time, the camera is supposed to be following the first player. This is not happening. I provide an option to "restart", which would resolve that issue, but I don't want this event happening in the first place.

More serious concerns GameObjects that were dynamically loaded. I am receiving "'GameObject' has been destroyed but you are still trying to access it." I am not sure where this is coming from, as I don't see where I had previously called "Destroy" anywhere. Furthermore, the objects dynamically created do appear in the hierarchy, when I am running the app inside Unity.

I think the root of my problem lies with the failing camera, but I'm not sure how to approach fixing it.

Does anyone have any recommendations?


Solution

  • It sounds like you need to make sure to call DontDestroyOnLoad to keep your object in memory between level loads:

    DontDestroyOnLoad(gameObjectToPreserve);
    

    Also, the following code from your example will quit your application before it can load your "Opening Screen":

    if(GUI.Button (new Rect (x, y, w, h), "Quit", buttonStyle))
    {
       Application.Quit();
       Application.LoadLevel("Opening Screen");
    }
    

    Remove the line "Application.Quit()" if you intend to return to the opening screen. You won't see this problem in the editor's preview mode because Application.Quit() doesn't do anything there.