我在2D游戏中使用A *寻路算法(据我了解,Unity Nav Meshes在2D中不起作用)。我希望能够为我的所有场景预先计算出导航网格,并将其保存在资源文件中,以便在播放器进入新场景时可以加载。无需记住要为每个场景单击“计算”-并记得在对导航网格进行更改后要重新计算所有场景-我希望能够以编程方式让Unity编辑器遍历每个场景并计算网格。
有没有一种方法可以在Unity编辑器中创建一个命令,该命令将迭代地打开编辑器中的每个场景并在该场景中的上运行方法MonoBehaviour
?另外,还有另一种方法可以完成我想做的事情吗?
是的你可以!
在editmode中,您不能使用,SceneManager
但必须使用EditorSceneManager
。
首先,您需要迭代的场景。
例如,可能是在Inspector中public static
带有列表的字段SceneAsset
,您可以在其中简单地引用场景
public static List<SceneAsset> Scenes = new List<SceneAsset>();
或者您可以通过脚本获取它们,例如仅用于使用添加到构建设置中的场景 EditorBuildSettings.scenes
List<EditorBuildSettingsScene> Scenes = EditorBuildSettings.scenes;
对于两者,您都可以获取场景路径列表,例如使用LinQSelect
(这基本上是foreach
循环的一种快捷方式),AssetDatabase.GetAssetPath
例如
List<string> scenePaths = Scenes.Select(scene => AssetDatabase.GetAssetPath(scene)).ToList();
对于EditorBuildSettingsScene从EditorBuildSettings.scenes
你也可以简单地使用
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 Editor的顶部菜单栏中添加一个YourMenu
只有一个条目的新菜单RunCalculation
。
注意:
由于这使用了很多EditorSceneManager
仅存在于UnityEditor
名称空间中的类型(等),因此您应该将整个脚本放置在一个Editor
文件夹中(以便在最终版本中将其忽略),或者使用诸如
#if UNITY_EDITOR
// ... code here
#endif
因此在构建中,代码也将被忽略。
请注意,到目前为止,我假设您也以editmode进行了计算。问题是,如果此计算依赖于任何方法Start
或某种Awake
方法,则必须在运行计算之前从该编辑器脚本手动调用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句