[英]Get name of next Scene in build settings in Unity3D?
因此,我想做的事情似乎應該非常簡單。 我需要獲取下一個場景的名稱 (而不是加載它),如構建設置中所列。
我以為我有一個簡單的解決方案,可以這樣做:
int currentIndex = SceneManager.GetActiveScene().buildIndex;
string nextSceneName = SceneManager.GetSceneAt(currentIndex + 1).name
但是顯然,“ GetSceneAt”不適用於構建設置中的場景,而是適用於SceneManager擁有的某種內部列表。
我所有的Google搜索都根據場景的特定命名順序提出解決方案,或者在構建之前將場景列表導出到文件中(手動導出列表),等等。我無法想象這么簡單的問題需要如此復雜的解決方案,這就是為什么我要問自己。
如何僅在構建設置中獲取下一個場景的名稱?
從Unity 5.5開始,這應該可以工作,如果您使用的是較低版本,請參見下文。
大多數人首先嘗試的最直接的方法是使用SceneManager.GetSceneByBuildIndex(buildIndex)
因為它返回帶有name屬性的Scene
對象。
但是...文檔中提到:
如果已將場景添加到給定的構建索引處的構建設置中並且已加載該場景,則此方法將返回有效的Scene。 如果尚未加載,則SceneManager無法返回有效的場景。
但是,所有操作並不會丟失,因為還有SceneUtility.GetScenePathByBuildIndex(buildIndex)
,它不依賴於已加載的場景。 它返回到場景的項目相對路徑,我們可以從中提取場景名稱。
public static class SceneUtilityEx
{
public static string GetNextSceneName()
{
var nextSceneIndex = SceneManager.GetActiveScene().buildIndex + 1;
if (nextSceneIndex < SceneManager.sceneCountInBuildSettings)
{
return GetSceneNameByBuildIndex(nextSceneIndex);
}
return string.Empty;
}
public static string GetSceneNameByBuildIndex(int buildIndex)
{
return GetSceneNameFromScenePath(SceneUtility.GetScenePathByBuildIndex(buildIndex));
}
private static string GetSceneNameFromScenePath(string scenePath)
{
// Unity's asset paths always use '/' as a path separator
var sceneNameStart = scenePath.LastIndexOf("/", StringComparison.Ordinal) + 1;
var sceneNameEnd = scenePath.LastIndexOf(".", StringComparison.Ordinal);
var sceneNameLength = sceneNameEnd - sceneNameStart;
return scenePath.Substring(sceneNameStart, sceneNameLength);
}
}
編輯:包括以下部分是出於歷史原因,它僅適用於Unity 5.4和某些早期版本。
是的,不幸的是你是對的,但是...你很幸運!
在閱讀完您的問題后,我為此創建了一個插件/資產,它是三個小腳本,應該“可以正常工作”,並且使用它實際上只是一行代碼:
var buildSceneRecords = BuildScenes.Records;
記錄包含編輯器構建設置中場景的名稱,路徑和索引。
您可以在這里獲取它: https : //github.com/sindrijo/unity3d-runtime-buildscenes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.