Source file unity-csharp/scene-flow/GameSession.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: a persistent object with DontDestroyOnLoad, a duplicate guard and the SceneManager.sceneLoaded event
// Related pages: [[unity-scene-management]], [[unity-gamemanager-pattern]]
 
using UnityEngine;
using UnityEngine.SceneManagement;
 
// Place this in the Title scene only. It survives every later scene load and
// remembers which level was played, so a separate GameOver scene can offer "Retry".
public class GameSession : MonoBehaviour
{
    public static GameSession Instance { get; private set; }
 
    public string LastLevelScene { get; private set; }
    public bool LastRunWon { get; private set; }
    public int Attempts { get; private set; }
 
    private void Awake()
    {
        // Returning to the Title scene loads a second GameSession: keep the first one.
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
 
        Instance = this;
        DontDestroyOnLoad(gameObject); // must be a root GameObject
    }
 
    private void OnEnable()
    {
        SceneManager.sceneLoaded += HandleSceneLoaded;
    }
 
    private void OnDisable()
    {
        SceneManager.sceneLoaded -= HandleSceneLoaded;
    }
 
    private void OnDestroy()
    {
        if (Instance == this)
        {
            Instance = null;
        }
    }
 
    public void RecordResult(string levelSceneName, bool won)
    {
        LastLevelScene = levelSceneName;
        LastRunWon = won;
        Attempts++;
    }
 
    // Runs after the new scene's Awake and OnEnable calls, before its Start calls.
    private void HandleSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (Instance != this)
        {
            return; // a duplicate that is about to be destroyed
        }
 
        Time.timeScale = 1f; // second safety net for the frozen-scene bug
        Debug.Log("Loaded '" + scene.name + "' (build index " + scene.buildIndex + ", " + mode + "). Attempts so far: " + Attempts);
    }
}