Tag Archives: unity3d 11 SceneManager

Summary of unity3d 11 SceneManager scene management usage

I. Unity level
Level loading and unloading during Unity use is a basic feature provided by most 3D engines.
because level switching is very common in games.
in previous releases Unity’s level switches used:

Application.loadedLevel();

Take a look at the Application class, which has more and more functions. Look only at levels related:

 [Obsolete("Use SceneManager.LoadScene")]
        public static void LoadLevel(string name);

        [Obsolete("Use SceneManager.LoadScene")]
        public static void LoadLevel(int index);

        [Obsolete("Use SceneManager.LoadScene")]
        public static void LoadLevelAdditive(string name);

        [Obsolete("Use SceneManager.LoadScene")]
        public static void LoadLevelAdditive(int index);
  //
        // Abstracts:
        //     ///
        //     Unloads all GameObject associated with the given scene. Note that assets are
        //     currently not unloaded, in order to free up asset memory call Resources.UnloadAllUnusedAssets.
        //     ///
        //
        // Parameter:
        //   index:
        //     Index of the scene in the PlayerSettings to unload.
        //
        //   scenePath:
        //     Name of the scene to Unload.
        //
        // Return Results:
        //     ///
        //     Return true if the scene is unloaded.
        //     ///
        [Obsolete("Use SceneManager.UnloadScene")]
        public static bool UnloadLevel(string scenePath);
        //
        // Abstracts:
        //     ///
        //     Unloads all GameObject associated with the given scene. Note that assets are
        //     currently not unloaded, in order to free up asset memory call Resources.UnloadAllUnusedAssets.
        //     ///
        //
        // Parameter:
        //   index:
        //     Index of the scene in the PlayerSettings to unload.
        //
        //   scenePath:
        //     Name of the scene to Unload.
        //
        // Return Results:
        //     ///
        //     Return true if the scene is unloaded.
        //     ///
        [Obsolete("Use SceneManager.UnloadScene")]
        public static bool UnloadLevel(int index);

Note:
this is the loading and unloading of levels in the previous Application.
of course there is now a new change in the new version (Unity5.3 above) that the SceneManager class handles.
SceneManager class Untiy
Since Unity5.3, Unity’s level switch has added new SceneManager classes to handle it.
of course has to be installed with Unity documentation help, and given the following path, it will know to open locally. Local links:

file:///C:/Program%20Files/Unity5.3.0/Editor/Data/Documentation/en/Manual/UpgradeGuide53.html
can also search the SceneManager to view in Unity.

#region Program Collections UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// H:\Unity\UnityProject\ShiftLevels\Library\UnityAssemblies\UnityEngine.dll
#endregion

using UnityEngine.Internal;

namespace UnityEngine.SceneManagement
{
    //
    // Parameter:
    //     ///
    //     Scene management at run-time.
    //     ///
    public class SceneManager
    {
        public SceneManager();


        public static int sceneCount { get; }
        //

        public static int sceneCountInBuildSettings { get; }


        public static Scene GetActiveScene();

        public static Scene[] GetAllScenes();
        // Parameter:
        //   index:
        //     Index of the scene to get. Index must be greater than or equal to 0 and less
        //     than SceneManager.sceneCount.
        public static Scene GetSceneAt(int index);

        // Return Results:
        //     ///
        //     The scene if found or an invalid scene if not.
        //     ///
        public static Scene GetSceneByName(string name);

        //     Searches all scenes added to the SceneManager for a scene that has the given
        //     asset path.
        //     ///
        //
        // Parameter:
        //   scenePath:
        //     Path of the scene. Should be relative to the project folder. Like: "AssetsMyScenesMyScene.unity".
        public static Scene GetSceneByPath(string scenePath);
        [ExcludeFromDocs]
        public static void LoadScene(int sceneBuildIndex);
        [ExcludeFromDocs]
        public static void LoadScene(string sceneName);

        // Parameter:
        //   sceneName:
        //     Name of the scene to load.
        //
        //   sceneBuildIndex:
        //     Index of the scene in the Build Settings to load.
        //
        //   mode:
        //     Allows you to specify whether or not to load the scene additively. See SceneManagement.LoadSceneMode
        //     for more information about the options.
        public static void LoadScene(int sceneBuildIndex, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);

        // Parameter:
        //   sceneName:
        //     Name of the scene to load.
        //
        //   sceneBuildIndex:
        //     Index of the scene in the Build Settings to load.
        //
        //   mode:
        //     Allows you to specify whether or not to load the scene additively. See SceneManagement.LoadSceneMode
        //     for more information about the options.
        public static void LoadScene(string sceneName, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);
        [ExcludeFromDocs]
        public static AsyncOperation LoadSceneAsync(int sceneBuildIndex);
        [ExcludeFromDocs]
        public static AsyncOperation LoadSceneAsync(string sceneName);

        // Parameter:
        //   sceneName:
        //     Name of the scene to load.
        //
        //   sceneBuildIndex:
        //     Index of the scene in the Build Settings to load.
        //
        //   mode:
        //     If LoadSceneMode.Single then all current scenes will be unloaded before loading.
        public static AsyncOperation LoadSceneAsync(int sceneBuildIndex, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);

        // Parameter:
        //   sceneName:
        //     Name of the scene to load.
        //
        //   sceneBuildIndex:
        //     Index of the scene in the Build Settings to load.
        //
        //   mode:
        //     If LoadSceneMode.Single then all current scenes will be unloaded before loading.
        public static AsyncOperation LoadSceneAsync(string sceneName, [DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode);
        //

        // Parameter:
        //   sourceScene:
        //     The scene that will be merged into the destination scene.
        //
        //   destinationScene:
        //     Existing scene to merge the source scene into.
        public static void MergeScenes(Scene sourceScene, Scene destinationScene);
        //
        // Abstracts:
        //     ///
        //     Move a GameObject from its current scene to a new scene. /// It is required that
        //     the GameObject is at the root of its current scene.
        //     ///
        //
        // Parameter:
        //   go:
        //     GameObject to move.
        //
        //   scene:
        //     Scene to move into.
        public static void MoveGameObjectToScene(GameObject go, Scene scene);
        //

        // Return Results:
        //     ///
        //     Returns false if the scene is not loaded yet.
        //     ///
        public static bool SetActiveScene(Scene scene);

        //     ///
        public static bool UnloadScene(string sceneName);
        //
        // Abstracts:
        //     ///
        //     Unloads all GameObjects associated with the given scene. Note that assets are
        //     currently not unloaded, in order to free up asset memory call Resources.UnloadAllUnusedAssets.
        //     ///
        //
        // Parameter:
        //   sceneBuildIndex:
        //     Index of the scene in the Build Settings to unload.
        //
        //   sceneName:
        //     Name of the scene to unload.
        //
        // Return Results:
        //     ///
        //     Returns true if the scene is unloaded.
        //     ///
        public static bool UnloadScene(int sceneBuildIndex);
    }
}

SceneManager for some operations to obtain scenes
(a)
SceneManager
class in UnityEngine. SceneManagement
description: runtime scene management.
static variable sceneCount: total number of scenes currently loaded. The number of scenarios loaded before
is returned.
sceneCountInBuildSettings: in BuildSettings number.
(b)
CreateScene: creates an empty new scenario at runtime, using the given name.
creates an empty new scenario at run time, using the given name.
new scenes will be added to the level with existing already open scenes. The path for the new scene will be empty. This function is used to create a scenario at run time. Create a scenario editor of time (for example, make editing scripts or tools you need to create the scene), using editorscenemanager. Newscene.

public static SceneManagement.Scene GetActiveScene()
live activity Scene.
description: gets the current active scenario.
the currently active scene will be used as the target to instantiate the new game object scene by the script.

using UnityEngine;
using UnityEngine.SceneManagement;

public class GetActiveSceneExample : MonoBehaviour
{
    void Start()
    {
        Scene scene = SceneManager.GetActiveScene();

        Debug.Log("Active scene is '" + scene.name + "'.");
    }
}

public static SceneManagement.Scene GetSceneAt(int index);
index: scene index. Indexes must be greater than or equal to 0 and less than Scenemanager. Scenecount.
Return:
returns a scenario reference based on the given parameters.
gets the list index of the scene manager in the scene being added:

using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using UnityEngine;
public class Example
{
    // adds a menu item which gives a brief summary of currently open scenes
    [MenuItem("SceneExample/Scene Summary")]
    public static void ListSceneNames()
    {
        string output = "";
        if (SceneManager.sceneCount > 0)
        {
            for (int n = 0; n < SceneManager.sceneCount; ++n)
            {
                Scene scene = SceneManager.GetSceneAt(n);
                output += scene.name;
                output += scene.isLoaded ?" (Loaded, " : " (Not Loaded, ";
                output += scene.isDirty ?"Dirty, " : "Clean, ";
                output += scene.buildIndex >=0 ?" in build)\n" : " NOT in build)\n";
            }
        }
        else
        {
            output = "No open scenes.";
        }
        EditorUtility.DisplayDialog("Scene Summary",output, "Ok");
    }
}

(5)
public static SceneManagement.Scene GetActiveScene();
gets the current active scenario.
the current active scenario will be used as the target to instantiate the new object by the script.

using UnityEngine;
using UnityEngine.SceneManagement;

public class GetActiveSceneExample : MonoBehaviour
{
    void Start()
    {
        Scene scene = SceneManager.GetActiveScene();

        Debug.Log("Active scene is '" + scene.name + "'.");
    }
}

public static void LoadScene(int sceneBuildIndex, SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);
public static void LoadScene(string sceneName, SceneManagement.LoadSceneMode mode = LoadSceneMode.Single);

SceneName: The name or path of the scene to load.
SceneBuildIndex: Index of scenarios under load in “Build Settings”.
Mode: Allows you to specify whether you want to load the add scene. See the LoadScene mode for more information about options.
LoadSceneMode: used when the player loads a scene.
Single: close all current scenes and load a new scene.
Additive: adds the scene to the currently loaded scene.
you can use this asynchronous version: LoadSceneAsync.

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleClass : MonoBehaviour {
    void Start () {
        // Only specifying the sceneName or sceneBuildIndex will load the scene with the Single mode
        SceneManager.LoadScene ("OtherSceneName", LoadSceneMode.Additive);
    }
}

Iv. Implementation code of 5.3
The code:

/**************************************************************************
Copyright:@maxdong
Author: maxdong
Date: 2017-07-04
Description:Loading levels can be loaded and unloaded in groups. Uses Unity version 5.3.0.
This is because it uses a class for scene management, which was added in 5.3.0 or later.
Test operation: Use the spacebar to switch between scenes, and then wait 5 seconds before starting the unload.
**************************************************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

[System.Serializable]
public class LevelOrder
{

    [Header("Name of each group of levels")]
    public string[] LevelNames;
}

public class ChangLevelsHasMain : MonoBehaviour
{
    [Header("List of All Levels")]
    public LevelOrder[] levelOrder;
    private static int index;
    private int totalLevels = 0;
    private int levelOrderLength;

    void Start ()
    {
        for (int i = 0; i < levelOrder.Length; i++)
        {
            totalLevels += levelOrder[i].LevelNames.Length;
        }

        if (totalLevels != SceneManager.sceneCountInBuildSettings)
        {

        }
        levelOrderLength = levelOrder.Length;
    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            bool isOk = LoadNextLevels();
            if (isOk)
            {
                InvokeRepeating("UnloadLastLevel", 2.0f, 5);
            }
        }
    }

    bool LoadNextLevels()
    {
        bool bResult = true;
        //index = index % levelOrderLength;
        if (index < 0 || index >= levelOrderLength)
        {
            bResult = false;
            return bResult;
        }

        int LoadTimes = levelOrder[index].LevelNames.Length;
        for (int i = 0; i < LoadTimes; i++)
        {
            SceneManager.LoadSceneAsync(levelOrder[index].LevelNames[i], LoadSceneMode.Additive);
        }
        return bResult;
    }

    void UnloadLastLevel()
    {
        if (index == 0)
        {
            index++;
            CancelInvoke("UnloadLastLevel");
            return;
        }
        // Previous Set of Levels
        int TmpLast = (index - 1) >= 0 ?(index - 1) : levelOrderLength - 1;
        int LoadTimes = levelOrder[index].LevelNames.Length;
        for (int i = 0; i < LoadTimes; i++)
        {
            Scene Tmp = SceneManager.GetSceneByName(levelOrder[index].LevelNames[i]);
            if (!Tmp.isLoaded)
            {
                return;
            }
        }

        // After the next level is fully loaded, unload the previous level.
        for (int i = 0; i < levelOrder[TmpLast].LevelNames.Length; i++)
        {
            SceneManager.UnloadScene(levelOrder[TmpLast].LevelNames[i]);
        }
        index++;
        CancelInvoke("UnloadLastLevel");
    }
}

That’s it. The
code primarily loads levels by group, and then unloads them by group.
test, press the space bar to load, each set of levels after a certain time, (set here in 5 seconds) automatically uninstall the previous set of levels. The main map is not unmounted and will always be there.
How is it set up?The first thing you need to do is put all the levels you need to work on in Build Setting. Otherwise, an error will be reported during loading.
as shown in the figure below:

Then hang the code on any object object on the main map.