Search code examples
c#unity-game-enginescene

Getting Scene Names at Runtime/Creating Scenes at runtime


I want to build a RTS Game in Unity version 5.3.xxx. I want to have a dropdown menu to select the level i want to play. I dont want to hardcode it in so how do i get the scene names at runtime? This is neccessary to add new Levels ingame. Thats the next question then. How do i create new scenes and add them to build path at runtime to use them ingame? for example in an map editor?

I cant use the UnityEditor to go through all scenes with foreeach, because its a editor class and these dont get into the final build..

Thanks


Solution

  • As of Unity 5.x, there are much more robust options for managing scenes at runtime.

    Getting the current scene name:

    SceneManager.GetActiveScene().name


    Getting a list of all scene names added to the SceneManager:

    var numScenes = SceneManager.sceneCount;
    List<string> sceneNames = new List<string>(numScenes);
    
    for (int i=0; i < numScenes; ++i)
    {
       sceneNames.Add(StageManager.GetSceneAt(i).name);
    }
    

    Creating new scene at runtime:

    var newScene = SceneManager.CreateScene(string sceneName);
    

    Adding new scenes to the build path at runtime:

    I'm fairly certain this is not possible nor recommended.

    If you want the functionality of a level editor in your game, consider writing your own method of serializing a scene so that it can be deserialized into an empty scene at runtime.


    See also: