Controlling Scene Changes in Unity Singleton

Controlling Scene Changes in Unity Singleton

Controlling Scene Changes in Unity Singleton

Hello everyone, in this post I will explain how to detect scene changes in singleton scripts. As you know, functions like Awake and Start in Unity only run when the scene is loaded, and in singleton scripts, once they run, they will not run again no matter how many times the scene changes. With the method I will explain below, you will be able to run the code that needs to run in your singleton scripts when the scene changes.

First, let's include the following Unity library in our project using "using".

using UnityEngine.SceneManagement; // The library we use for operations such as changing the scene.

Then, with the following codes, we can detect whether the scene has changed.

private void OnEnable()
  {
    SceneManager.sceneLoaded += OnSceneLoad; // The code we use to detect scene changes.
  }

  void OnSceneLoad(Scene scene, LoadSceneMode mode) // The function that is called as a result of the changed scene.
  {
    Debug.Log(scene.name); // Here we write the operations we want to perform after the scene changes.
    // Here you can use the scene.name command to call the name of the loaded scene.
    // You can use the scene.buildIndex command to call the scene number of the loaded scene.
    // With mode, you can find out in which mode the scene was loaded.
 
  }
  
  private void OnDisable()
  {
    SceneManager.sceneLoaded -= OnSceneLoad; // The code snippet that ends the code we used to detect scene changes.
  }

Yes friends, I have also provided explanations along with the codes. The point you need to pay attention to here is that these commands work with Action, and therefore you should use the OnEnable and OnDisable commands, and in order not to affect the performance of your game, you should not forget to use the OnDisable command.

If you have any questions in your mind, you can ask them in the comment section below. I wish you a good day.