How to load a scene using Unity Scene Manager

Scenes are part of every game. Changing scene based on the game’s story or based on the menu is a common functionality required in all game engines. In Unity, the Scene Manager does that job. The Unity Scene Manager manages your scenes at runtime. It is a well-equipped class of Unity engine that we can use to effortlessly switch between scenes. Scene management is the next step in our learn Unity series.

First, let’s start with the basics of the Unity Scene manager’s script. All of the scene manager’s properties and methods are static. This means you can access them from any script without having to reference them. I will demonstrate this in the coming example.

To be able to use the Unity scene manager, you need to make sure you have included UnityEngine.SceneManagement in your script header as shown in the script below.

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class ExampleScript : MonoBehaviour
{
   
    void Update()
    {
        
        
    }

}

If you want to manage scenes without writing codes the asset below is really useful.

Unity Scene Manager Properties

The scene manager has 2 basic properties:

  • sceneCount: Total number of scenes that are currently loaded.
  • sceneCountInBuildSettings: Number of scenes that are currently added and active in your Unity Build Settings.

These properties can come in handy if you need to keep track of the number of loaded scenes. Here’s an example script that uses the Unity scene manager properties.

Example code to use sceneCount and sceneCountInBuildSettings properties.

You might be wondering, how can there be more than one scene? Well, it is possible, and it’s called Additive loading. You can load a scene on top of another scene, and have them both renderer and run their scripts at the same time. This may be bad for performance, so please keep that in mind when using it.

How to use Scene Manager in Unity.

Loading and unloading scenes can depend on the type of game you are making. We have listed some commonly used methods in Unity Scene Manager.

Get the current scene name in Unity

You can check which scene is currently loaded by using SceneManager.GetActiveScene() This will return a string with the scene name that is currently active. In the case where there are multiple scenes active, it will return the first scene that was active. Here is a sample code to log the current scene name.

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleScript : MonoBehaviour
{
   
    void Update()
    {
        
        Debug.Log(SceneManager.GetActiveScene().name);
        
    }

}

Load scene in Unity

Loading a scene is very simple. You simply need to call the method SceneManager.LoadScene() and tell it which scene you would like to load. Unity LoadScene() function takes a string as input but it can also be overloaded with a number.

To load a scene, it must be added to the build settings, if not LoadScene() will return an error.

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleScript : MonoBehaviour
{
   
    void Start()
    {
        
        Debug.Log("Loading New Scene");
        SceneManager.LoadScene("TestScene");
        
    }

}

In the above script, as soon as the scene starts, we log a message and load a scene called “TestScene”. The name of the scene is case sensitive, so be careful while typing the name. You can also replace the name with the build index number in build settings like this SceneManager.LoadScene(2).

Additive Loading

As mentioned before, you can also load a scene on top of another scene. For this example, let’s say we just completed the game, and want to load a leaderboard. We could do this on the same scene, but if for some reason, we need to have the leaderboard on a separate scene, we can simply load it onto my current scene. You can also create a leaderboard within the scene similar to creating a pause menu in Unity.

It is very similar to loading a single scene, except you also add a LoadSceneMode parameter to specify whether the scene should load additively, or as a single scene.

Note: If the LoadSceneMode parameter is not added, the scene will load as Single by default.

Here is the code to load a scene additively

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleScript : MonoBehaviour
{
   
    void Start()
    {        
        Debug.Log("Loading New Scene");
        SceneManager.LoadScene("TestScene",LoadSceneMode.Additive);        
    }

}

SetActiveScene()

You need to specify which is the active scene when using additive loading. In the example below, when the player gets 100 points, the leaderboard scene is set to active.

We are using the GetSceneByName() function to get the scene and loading it using SetActiveScene().

Sample code to set a scene as active

Another important feature is that, when you instantiate a prefab in Unity, it will put that object into the currently active scene, so if you have multiple scenes loaded, and you would like to instantiate an object, or delete an object by name, or reference any object, Unity will perform that action based on your current active scene.

How to Load a Scene only Once using PlayerPrefs

Sometimes you need to load a scene only when the player is playing the game for the first time. For example, a tutorial on how to play the game needs to be loaded only once during game start.

What we are going to do

  • Save an integer to disk after scene load.
  • Check if the integer is equal to one before loading the scene next time.
  • If it’s one we load the non-tutorial scene.
  • Else load the tutorial scene.
using UnityEngine;
using UnityEngine.SceneManagement;

public class sceneload : MonoBehaviour
{

void Start()
{
     int tutorial_loaded= PlayerPrefs.GetInt("Loaddata", 0);
     If(tutorial_loaded==1)
     {
      SceneManager.loadScene("Not_tutorial_scene");
     }
     else
     {
      PlayerPrefs.SetInt("Loaddata",1);
      PlayerPrefs.Save();
      SceneManager.loadScene("tutorial_scene");
     }

}


}
    

How to reload a scene in Unity

Sometimes it is required to reload a scene when the player fails to complete the task. In Unity, you can get the active scene and load it like any other scene based on the conditions required. As in the example scripts above, you can load the scene either using the scene index or scene name.

using UnityEngine;
using UnityEngine.SceneManagement;

public class sceneload : MonoBehaviour
{

void Update()
{
     if(player_failed)
      { 
         SceneManager.LoadScene(SceneManager.GetActiveScene().name);
      }

}


}

How to create a menu in Unity using Scene manager

Unity Scene manager can be used to do a lot of things. The most common example is the main menu. You can switch to a different scene when you press a button on the menu. Let’s see how to create a simple menu using loadscene() function of Scene manager.

The very first step is to create a script. We need a public function that we can call on button press. The function will take in the scene name and load it.

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleScript : MonoBehaviour
{   
    public void LoadScene(string SceneName)
    {        
        SceneManager.LoadScene(SceneName);       
    }

}

Important note: The method must be public, otherwise it cannot be accessed outside the script. This includes buttons as well, so bear that in mind.

Now we have the script setup. Let’s set up the scene and make use of the method we created.

  • Right-click in your hierarchy, and navigate to UI > Button to create a button in your scene (This will automatically create a canvas if you don’t have one).
Adding a button to the scene
  • Right-click in your hierarchy and select Create Empty. This is where we will put our script that holds the level-changing method.
Creating empty game object
  • Rename the Empty game object to “SceneManager”.
  • Attach the script we created in this tutorial to the SceneManager game object we just created. You can do this by selecting Add Component in the inspector and searching for the script by name.
attaching the script component
  • Select the button game object you created earlier
  • When your button is selected, in the inspector window, find the button component and find the On Click Event section.
adding event to button
  • Click on the + button on the bottom right of the On Click event section to add an event
  • Drag the SceneManager game object into the newly created event.
adding script to event
  • Click on the No Function drop down menu.
  • Navigate to, and select ExampleScript > LoadScene.
selecting function to call on button press
  • Type in the name of the scene that you want to load when this button is pressed. Make sure that the spelling of the scene is exactly the same as the one in your project. It is also case sensitive, so an even better option is to copy/paste the name from your scene asset into the field.
  • Finally, run the scene and press the button. Your new scene should load! 

That’s it, you have successfully created a menu button to load a new scene.

How to Unload a scene in Unity

If you have multiple scenes loaded, you should always unload the scene that you are not using. This will improve your game’s performance, and would also keep your project clean as you are working.

You can Unload a scene by using SceneManager.UnloadSceneAsync(). Async means that it will unload your scene asynchronously. This is good, as it won’t interrupt the game, so you can unload scenes and continue playing/working at the same time.

sample script to Unloading a scene

Similar to the previous examples, we have just added a line at line 24, which means after loading the leaderboards, we unload Level 1 so that we can now only see the leaderboard.

This is pretty similar to simply loading the leaderboard scene as a Single. But by adding these extra steps, you can maybe play some animations, some audio and particles, or whatever it may be in your scene while the leaderboard is up. Then when all your processes on Level 1 are complete, you can unload it.

Unity Scene Manager Events

There are 3 events associated with the Unity Scene Manager, and they can come in handy in a lot of situations:

  • SceneManager.activeSceneChanged: This event is triggered whenever the active scene is changed. We have demonstrated this in the previous pages here.
  • SceneManager.sceneLoaded: This event is triggered whenever a new scene is loaded. A scene that is loaded is different from active. When a new scene is loaded, the activeSceneChanged event is NOT called. That event is only called when you explicitly decide to set the active scene.
  • SceneManager.sceneUnloaded: This event is similar to the sceneLoaded, it is triggered when a scene is Unloaded.

You can use these events by subscribing to them just as you would with any other Unity event. And when a scene is loaded, for example, you can do something in your game. Here’s a code example. In the below code, we subscribe to sceneLoaded and sceneUnloaded events using two different functions. These functions are called when a scene is loaded or unloaded.

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleScript : MonoBehaviour
{   
    public void OnEnable()
    {        
        SceneManager.sceneLoaded+=OnSceneLoaded;
        SceneManager.sceneUnloaded+=OnSceneUnloaded;
    }

    private void OnSceneUnloaded(Scene scene)
    {
        Debug.Log("Scene Loaded: "+scene.name);
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("Scene UnLoaded: "+scene.name);
        Debug.Log("Scene Mode: "+mode);
    }
}

We first need to hook up the Events so that when they get invoked, we can call a method. This means that whenever a new scene is loaded, the method OnSceneLoaded will be called. And whenever a scene is Unloaded, the method OnSceneUnloaded will be called.

This is useful if you want to do something specific when a scene is loaded and unloaded, for example, when a scene loads, you may want to initialize some variables to prepare the new level. You could also use this to save your game. The possibilities are endless.

Scene Manager does not exit error

If you get the above error, it is mostly because you missed the namespace on the top. Add using UnityEngine.SceneManagement to your script.

If you still get the error then check the spellings in your script. Remember Unity functions are case sensitive.

The ‘S’ and ‘M’ are in capital letters in SceneManager.

As you can see the Unity scene manager is of many uses. You can test out the different functions in different ways. If you need clarification on anything, feel free to leave a comment below.

For our next tutorial, we will create a health bar in Unity.

2 thoughts on “How to load a scene using Unity Scene Manager”

  1. Got it easy after reading this content.Saved my time efforts.You are really so creative and innovative sir.Thank you

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading