0
0
Unityframework~5 mins

Scene loading and unloading in Unity

Choose your learning style9 modes available
Introduction

Loading and unloading scenes lets you change what the player sees and interacts with. It helps keep your game organized and saves memory by only using what is needed.

When moving from one level to another in a game.
When opening or closing menus or UI screens.
When loading parts of a large world step-by-step.
When freeing up memory by removing scenes no longer needed.
Syntax
Unity
using UnityEngine.SceneManagement;

// To load a scene by name
SceneManager.LoadScene("SceneName");

// To load a scene additively (keep current scenes)
SceneManager.LoadScene("SceneName", LoadSceneMode.Additive);

// To unload a scene by name
SceneManager.UnloadSceneAsync("SceneName");

Use LoadSceneMode.Additive to load a scene without removing the current one.

Unloading scenes frees memory but only works on scenes loaded additively.

Examples
This loads the "MainMenu" scene and replaces the current scene.
Unity
SceneManager.LoadScene("MainMenu");
This loads "Level2" on top of the current scene, so both run together.
Unity
SceneManager.LoadScene("Level2", LoadSceneMode.Additive);
This unloads the "Level1" scene asynchronously to free memory.
Unity
SceneManager.UnloadSceneAsync("Level1");
Sample Program

This script listens for key presses. Pressing 'L' loads a scene called "GameScene" without removing the current scene. Pressing 'U' unloads "GameScene" to free memory.

Unity
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneSwitcher : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
            // Load the "GameScene" additively
            SceneManager.LoadScene("GameScene", LoadSceneMode.Additive);
            Debug.Log("GameScene loaded additively.");
        }

        if (Input.GetKeyDown(KeyCode.U))
        {
            // Unload the "GameScene"
            SceneManager.UnloadSceneAsync("GameScene");
            Debug.Log("GameScene unloading started.");
        }
    }
}
OutputSuccess
Important Notes

Always check that the scene name matches exactly what is in your build settings.

Loading scenes additively is useful for UI or multi-part worlds.

Unloading scenes is asynchronous, so it happens over time without freezing the game.

Summary

Use SceneManager.LoadScene to load scenes by name.

Use LoadSceneMode.Additive to keep current scenes when loading new ones.

Unload scenes with SceneManager.UnloadSceneAsync to save memory.