是的,你可以!
在编辑模式下,您不能使用SceneManager,但必须使用EditorSceneManager。
首先,您需要要迭代的场景。
例如可以是public static 字段,在 Inspector 中包含 SceneAsset 列表,您只需在其中引用场景
public static List<SceneAsset> Scenes = new List<SceneAsset>();
或者您可以通过脚本获取它们,例如仅使用使用EditorBuildSettings.scenes添加到构建设置中的场景
List<EditorBuildSettingsScene> Scenes = EditorBuildSettings.scenes;
对于两者,您都可以获得场景路径列表,例如使用LinQ Select(这基本上是foreach循环的一种快捷方式)和AssetDatabase.GetAssetPath like
List<string> scenePaths = Scenes.Select(scene => AssetDatabase.GetAssetPath(scene)).ToList();
对于来自EditorBuildSettings.scenes 的EditorBuildSettingsScene,您也可以简单地使用
List<string> scenePaths = Scenes.Select(scene => scene.path).ToList();
现在您可以使用EditorSceneManager.OpenScene、EditorSceneManager.SaveScene 和EditorSceneManager.CloseScene(如果您需要AssetDatabase.SaveAssets)来遍历它们并完成您的工作
foreach(string scenePath in scenePaths)
{
// Open a scene e.g. in single mode
var currentScene = EditorSceneManager.OpenScene(scenePath);
/* Do your calculation for currentScene */
// Don't know if it makes changes to your scenes .. if not you can probably skip this
EditorSceneManager.SaveScene(currentScene);
// Finally Close and remove the scene
EditorSceneManager.CloseScene(currentScene, true);
}
// you might be doing changes to an asset you want to save when done
AssetDatabase.SaveAssets();
在开始之前,您可能应该要求使用 EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo 保存当前打开的场景
if(EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
// Saved => the foreach loop here
}
else
{
// aborted => do nothing
}
为了最终启动该方法,最简单的方法是添加[MenuItem]
public static class Calculation
{
[MenuItem("YourMenu/RunCalculation")]
public static void RunCalculation()
{
// all the before mentioned snippets here
// depending how exactly you want to do it
}
}
这将在 Unity 编辑器的顶部菜单栏中添加一个新菜单 YourMenu,其中包含一个条目 RunCalculation。
注意:
由于这使用了许多仅存在于 UnityEditor 命名空间中的类型(EditorSceneManager 等),您应该将整个脚本放在 Editor 文件夹中(因此在最终构建中将被忽略)或使用预处理器喜欢
#if UNITY_EDITOR
// ... code here
#endif
所以在构建中代码也被忽略了。
请注意,到目前为止,我假设您还在编辑模式下进行了计算。问题是,如果此计算依赖于任何 Start 或 Awake 方法,则必须在运行计算之前从该编辑器脚本手动调用它。