Search code examples
c#unity-game-enginegame-engine

Unity C# Scene Management


I have a scene and a button to restart the scene when game is over. I also have a OnDestroy() function in a script of a game object. Everything works just fine but I am curious about if the OnDestroy() function will be called if I start the scene again with tracking the active scene.

When game is over and if player presses the restart button this function will be called;

private void reStart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

If player goes directly to the menu scene, OnDestroy() function is called.

My question is, by calling the reStart() function, will OnDestroy() function be called as well or should I seek for another solution? If no, is the only way going to another scene and then going back to play scene or is there another way to do that?

Many thanks for the answers.


Solution

  • What makes this scene different to your menu scene?

    Yes, OnDestroy is called.

    By default the scene mode for LoadScene is

    Single: Closes all current loaded Scenes and loads a Scene.

    So you load a "new" scene which unloads the current one -> destroys current objects.

    (Except if you are using DontDestroyOnLoad somewhere .. which seems not the case since otherwise it also wouldn't get destroyed if you load the menu scene.)

    Anyway, you could easily find it out yourself:

    private void OnDestroy()
    {
        Debug.Log($"I just got destroyed {name}");
    }
    

    Just a sidenote I would usually prefer to go by Scene.buildIndex instead of the Scene.name.

    • Scenes in different folders could have the same name. (Might be paranoid ;) )
    • I guess it's slightly faster to use int instead of string (might be micro improvement)