#if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; /// /// Unity 编辑器每隔 10 分钟自动保存一次打开的场景和资源。 /// 菜单:Tools / Auto Save /// [InitializeOnLoad] public static class AutoSave { private const string PrefEnabled = "UITools.AutoSave.Enabled"; private const double IntervalSeconds = 10 * 60; // 10 分钟 private static double _nextSaveTime; private static bool Enabled { get => EditorPrefs.GetBool(PrefEnabled, true); set => EditorPrefs.SetBool(PrefEnabled, value); } static AutoSave() { _nextSaveTime = EditorApplication.timeSinceStartup + IntervalSeconds; EditorApplication.update += OnUpdate; } private static void OnUpdate() { if (!Enabled) return; if (EditorApplication.isPlayingOrWillChangePlaymode) return; if (EditorApplication.timeSinceStartup < _nextSaveTime) return; _nextSaveTime = EditorApplication.timeSinceStartup + IntervalSeconds; DoSave(); } private static void DoSave() { EditorSceneManager.SaveOpenScenes(); AssetDatabase.SaveAssets(); Debug.Log($"[AutoSave] 已自动保存 — {System.DateTime.Now:HH:mm:ss}"); } [MenuItem("Tools/Auto Save/立即保存")] private static void SaveNow() { DoSave(); _nextSaveTime = EditorApplication.timeSinceStartup + IntervalSeconds; } [MenuItem("Tools/Auto Save/启用", true)] private static bool ValidateEnable() => !Enabled; [MenuItem("Tools/Auto Save/启用")] private static void Enable() { Enabled = true; _nextSaveTime = EditorApplication.timeSinceStartup + IntervalSeconds; Debug.Log("[AutoSave] 已启用(每 10 分钟)"); } [MenuItem("Tools/Auto Save/禁用", true)] private static bool ValidateDisable() => Enabled; [MenuItem("Tools/Auto Save/禁用")] private static void Disable() { Enabled = false; Debug.Log("[AutoSave] 已禁用"); } } #endif