0
0
Unityframework~5 mins

Scene creation and management in Unity

Choose your learning style9 modes available
Introduction

Scenes help organize different parts of your game or app. Managing scenes lets you switch between levels, menus, or different views easily.

When you want to separate your game into levels or stages.
When you need a main menu and a gameplay area as different screens.
When loading a new environment or area in your game.
When you want to unload unused parts to save memory.
When testing different parts of your game independently.
Syntax
Unity
using UnityEngine.SceneManagement;

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

// Load a scene asynchronously
SceneManager.LoadSceneAsync("SceneName");

// Get the active scene
Scene activeScene = SceneManager.GetActiveScene();

// Unload a scene
SceneManager.UnloadSceneAsync("SceneName");

Always add your scenes to the Build Settings in Unity to load them by name.

Use asynchronous loading to keep your game smooth during scene changes.

Examples
This loads the scene named "MainMenu" immediately, replacing the current scene.
Unity
SceneManager.LoadScene("MainMenu");
This loads "Level1" in the background without freezing the game.
Unity
SceneManager.LoadSceneAsync("Level1");
This gets the current active scene and prints its name to the console.
Unity
Scene current = SceneManager.GetActiveScene();
Debug.Log(current.name);
This unloads the "Tutorial" scene to free up memory.
Unity
SceneManager.UnloadSceneAsync("Tutorial");
Sample Program

This script listens for number keys 1, 2, and 3. Pressing 1 loads the "MainMenu" scene immediately. Pressing 2 loads "Level1" asynchronously. Pressing 3 prints the current scene's name in the console.

Unity
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneSwitcher : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            SceneManager.LoadScene("MainMenu");
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            SceneManager.LoadSceneAsync("Level1");
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            Scene active = SceneManager.GetActiveScene();
            Debug.Log($"Current Scene: {active.name}");
        }
    }
}
OutputSuccess
Important Notes

Make sure all scenes you want to load are added in Unity's Build Settings.

Use asynchronous loading to avoid freezing the game during scene changes.

You can load multiple scenes additively to combine content from different scenes.

Summary

Scenes organize your game into separate parts like levels or menus.

Use SceneManager to load, unload, and get information about scenes.

Asynchronous loading helps keep your game smooth during scene changes.