How to get scene name at certain buildIndex
There is way to get currently loaded scene name by Application.loadedLevelName
, but is there a way to get a name of the scene at certain buildIndex or a name of the scene that is at current buildIndex + 1?
Answer by hexagonius · Oct 25, 2016 at 08:20 PM
I think the only access point is mentioned here:
https://docs.unity3d.com/ScriptReference/EditorBuildSettings-scenes.html
The 5.5b documentation states, that a EditorBuildSettingsScene only has a path as the only string information. The exampled from the link above makes use of the AssetDatabase class to get the full path which contains the name of the level (acutally I don't know if not the path from EditorBuildSettingsScene already contains that).
Nevertheless, it seems a little complicated, but that's the best I came up with.
Answer by JimmyCushnie · Apr 18, 2018 at 06:50 PM
I managed to figure this out. Here you go, future googlers:
private static string NameFromIndex(int BuildIndex)
{
string path = SceneUtility.GetScenePathByBuildIndex(BuildIndex);
int slash = path.LastIndexOf('/');
string name = path.Substring(slash + 1);
int dot = name.LastIndexOf('.');
return name.Substring(0, dot);
}
Answer by ibx00 · Feb 04, 2020 at 09:47 AM
System.IO.Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(yourBuildIndex));
GetScenePathByBuildIndex
returns the path and GetFileNameWithoutExtension
returns the name of the file without the path and extension. So the result of this line is the exact scene name as per the given index you've given
Cheers :)
Answer by JPoenisch · Jul 04, 2019 at 04:48 AM
There is an easier way:
private static string GetSceneNameByIndex(int buildIndex)
{
if(buildIndex > SceneManager.sceneCountInBuildSettings - 1)
{
Debug.LogErrorFormat("Incorrect buildIndex {0}!", buildIndex);
return null;
}
var scene = SceneManager.GetSceneByBuildIndex(buildIndex);
return scene.name;
}
private static string GetNextSceneName()
{
return GetSceneNameByIndex(SceneManager.GetActiveScene().buildIndex + 1);
}
If the buildIndex is the actual buildIndex as shown in the editor build settings window, you don't need to +1 to Scene$$anonymous$$anager.sceneCountInBuildSettings.
Other than that this is the best answer imo.
I think it should have been a -
^^ Don't know why I have put a +
there actually
Answer by stslavik · Jul 29, 2019 at 01:57 AM
Came looking for the same issue, and got hung up on the SceneManager handling already loaded scenes, which didn't necessarily help. Here's the solution I came up with:
public static string GetSceneNameFromBuildIndex(int index) {
string scenePath = SceneUtility.GetScenePathByBuildIndex(index);
string sceneName = System.IO.Path.GetFileNameWithoutExtension(scenePath);
return sceneName;
}