using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; public class ScenePostProcessor : PostProcessor { /// /// 原场景 /// private Scene Scene { get; set; } /// /// 后处理场景 /// private Scene ClonedScene { get; set; } /// /// 后处理场景根路径 /// private const string SCENE_POSTPROCESS_DIR = "Assets/Art_Out/AutoGen/PostProcessScenes"; /// /// 场景后处理根文件路径 /// protected override string ResourcesBaseDir => SCENE_POSTPROCESS_DIR; /// /// 后处理场景父路径 /// protected override string PostProcessFolderName => Path.GetFileNameWithoutExtension(scenePath.Replace("/", "_")); /// /// 原场景资源 /// protected override Object AssetToPostProcess => AssetDatabase.LoadAssetAtPath(scenePath); /// /// 后处理场景路径 /// protected override string OutputAssetPath => $"{ProcessedResourceDir}/{sceneName}_{SCENE_POST_PROCESS_NAME}.unity"; /// /// 原场景路径 /// private string scenePath; /// /// 原场景名字 /// private string sceneName; protected override void Init(PostProcessInstructor postProcessInstructor) { base.Init(postProcessInstructor); Scene = postProcessInstructor.gameObject.scene; // 保存场景名字及路径 scenePath = Scene.path; sceneName = Scene.name; } protected override PostProcessInstructor Clone() { var sceneCount = SceneManager.sceneCount; for (int i = 0; i < sceneCount; i++) { var scene = SceneManager.GetSceneAt(i); if (scene.name.Contains(SCENE_POST_PROCESS_NAME)) EditorSceneManager.CloseScene(scene, true); } AssetDatabase.CopyAsset(Scene.path, OutputAssetPath); AssetDatabase.Refresh(); ClonedScene = EditorSceneManager.OpenScene(OutputAssetPath, OpenSceneMode.Additive); EditorSceneManager.MarkAllScenesDirty(); var result = FindInstructorInScene(ClonedScene); // 关闭原始场景 CloseOriginalScene(); return result; } /// /// 关闭原始场景 /// private void CloseOriginalScene() { try { if (SceneManager.sceneCount > 1) { Debug.Log($"关闭原始场景: {Scene.name}"); EditorSceneManager.CloseScene(Scene, true); } else { Debug.LogWarning("只有一个场景打开,无法关闭原始场景,需要至少保留一个场景。"); } } catch (System.Exception ex) { Debug.LogError($"关闭原始场景时出错: {ex.Message}"); } } protected override void AfterAll(bool destroyAfterPostProcess) { EditorSceneManager.SaveOpenScenes(); EditorUtil.AddPathToAddressable(ProcessedResourceDir, SCENE_ADDRESSABLE_GROUP); if (destroyAfterPostProcess) EditorSceneManager.CloseScene(ClonedScene, true); EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(ClonedScene.path)); } }