Search code examples
c#unity-game-enginescene-manager

Unity - unable to list all scenes in a project


In my app, I wanted to get a list of certain scenes and their build indices at start up of a particular scene. The probability is that none of the scenes has yet been loaded.

To do this I tried SceneManager.GetSceneByName() - I have the names of the relevant scenes. Nothing came back.

Looking at the docs it seemed this should work. However looking at the similar GetSceneByIndex() that does state it only works for loaded scenes, and I am assuming - thought it does not say so - the same applies to GetSceneByName().

So, I have not managed to find a way of listing all the available, but maybe not yet loaded, scenes. So far I have hard coded the relevant build indicies but I do not like that.

is there a way of doing this?


Solution

  • In general it makes sense that you can not get any reference to a Scene that is not loaded yet. Even using SceneManager.GetSceneByBuildIndex states

    This method will return a valid Scene if a Scene has been added to the build settings at the given build index AND the Scene is loaded. If it has not been loaded yet the SceneManager cannot return a valid Scene.


    What you can get however are at least all scene paths/names by using SceneUtility.GetScenePathByBuildIndex by iterating over SceneManager.sceneCountInBuildSettings

    int sceneCount = SceneManager.sceneCountInBuildSettings;     
    string[] scenes = new string[sceneCount];
    
    for( int i = 0; i < sceneCount; i++ )
    {
       scenes[i] = SceneUtility.GetScenePathByBuildIndex(i);
    }
    

    These would be the full scene paths. If you rather only want the scene name itself (but possible duplicates) you could probably instead use

    scenes[i] = Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(i));