using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; [InitializeOnLoad] public class AutoSaveBeforePlay { // 静态构造函数,在Unity编辑器启动时调用 static AutoSaveBeforePlay() { // 注册回调,当进入播放模式时触发 EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } // 当播放模式状态发生变化时调用 private static void OnPlayModeStateChanged(PlayModeStateChange state) { // 如果即将进入播放模式且场景未保存,则保存场景 if (state == PlayModeStateChange.ExitingEditMode) { AutoSaveScene(); } } // 自动保存当前场景 private static void AutoSaveScene() { // 获取当前场景路径 string scenePath = UnityEngine.SceneManagement.SceneManager.GetActiveScene().path; if (!string.IsNullOrEmpty(scenePath)) { // 保存当前场景 EditorSceneManager.SaveScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene()); Debug.Log("Scene auto-saved before entering play mode: " + scenePath); } else { Debug.LogWarning("Scene is not saved. Please save the scene manually."); } // 保存所有的资产(如 prefabs、脚本等) AssetDatabase.SaveAssets(); Debug.Log("All assets auto-saved."); } }