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

// GDnD wiki example
// Demonstrates: loading scenes by name and build index, restarting, returning to the menu and quitting (Unity 6)
// Related pages: [[unity-scene-management]], [[unity-gamemanager-pattern]]
 
using UnityEngine;
using UnityEngine.SceneManagement;
 
// Put one SceneFlow on a GameObject in every scene that has buttons, then wire
// each Button's On Click () to one of the public methods below.
public class SceneFlow : MonoBehaviour
{
    [SerializeField] private string menuSceneName = "Title";
    [SerializeField] private string firstLevelSceneName = "Level1";
 
    public void StartGame()
    {
        LoadScene(firstLevelSceneName);
    }
 
    public void LoadMenu()
    {
        LoadScene(menuSceneName);
    }
 
    // Reload the scene that is open now. Using the build index avoids typos in names.
    public void Restart()
    {
        LoadByIndex(SceneManager.GetActiveScene().buildIndex);
    }
 
    // Load the next scene in the Build Profiles scene list, or go back to the menu after the last one.
    public void LoadNextLevel()
    {
        int next = SceneManager.GetActiveScene().buildIndex + 1;
        if (next < SceneManager.sceneCountInBuildSettings)
        {
            LoadByIndex(next);
        }
        else
        {
            LoadMenu();
        }
    }
 
    // From a GameOver or Win scene, the active scene is no longer the level,
    // so ask the persistent GameSession which level was played last.
    public void RetryLastLevel()
    {
        if (GameSession.Instance != null && !string.IsNullOrEmpty(GameSession.Instance.LastLevelScene))
        {
            LoadScene(GameSession.Instance.LastLevelScene);
        }
        else
        {
            StartGame();
        }
    }
 
    // Takes a string, so a Button's On Click () can pass any scene name typed in the Inspector.
    public void LoadScene(string sceneName)
    {
        if (!Application.CanStreamedLevelBeLoaded(sceneName))
        {
            Debug.LogError("Scene '" + sceneName + "' is not in the scene list. Add it in File > Build Profiles.");
            return;
        }
 
        Time.timeScale = 1f; // a paused or slowed game must not stay frozen in the next scene
        SceneManager.LoadScene(sceneName);
    }
 
    private void LoadByIndex(int buildIndex)
    {
        if (!Application.CanStreamedLevelBeLoaded(buildIndex))
        {
            Debug.LogError("No scene at build index " + buildIndex + ". Check the scene list in File > Build Profiles.");
            return;
        }
 
        Time.timeScale = 1f;
        SceneManager.LoadScene(buildIndex);
    }
 
    public void Quit()
    {
        Debug.Log("Quit requested (ignored in the Editor).");
        Application.Quit();
    }
}