using System.IO; using UnityEditor; using UnityEngine; using AppleHills.Core.Settings; namespace Editor.Tools { /// /// Editor script that automatically clears saves before entering play mode /// if the autoClearSaves setting is enabled in DebugSettings /// [InitializeOnLoad] public static class AutoClearSavesOnPlay { static AutoClearSavesOnPlay() { EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } private static void OnPlayModeStateChanged(PlayModeStateChange state) { // Only act when entering play mode (before the scene starts playing) if (state != PlayModeStateChange.ExitingEditMode) return; // Try to load the debug settings DebugSettings debugSettings = LoadDebugSettings(); if (debugSettings == null) { Debug.LogWarning("[AutoClearSaves] Could not find DebugSettings asset. Auto-clear saves disabled."); return; } // Check if auto-clear is enabled if (!debugSettings.AutoClearSaves) { return; } // Execute the clear saves logic ClearSavesFolder(); } private static DebugSettings LoadDebugSettings() { // Try to find the DebugSettings asset in the project string[] guids = AssetDatabase.FindAssets("t:DebugSettings"); if (guids.Length == 0) { return null; } // Load the first found DebugSettings asset string path = AssetDatabase.GUIDToAssetPath(guids[0]); return AssetDatabase.LoadAssetAtPath(path); } private static void ClearSavesFolder() { // Construct the save folder path (matches SaveLoadManager.DefaultSaveFolder) string saveFolder = Path.Combine(Application.persistentDataPath, "GameSaves"); if (!Directory.Exists(saveFolder)) { Debug.Log("[AutoClearSaves] Save folder does not exist, nothing to clear."); return; } try { // Delete all files in the save folder string[] files = Directory.GetFiles(saveFolder); int deletedCount = 0; foreach (string file in files) { File.Delete(file); deletedCount++; } if (deletedCount > 0) { Debug.Log($"[AutoClearSaves] Automatically deleted {deletedCount} save file(s) before entering play mode"); } } catch (System.Exception ex) { Debug.LogError($"[AutoClearSaves] Failed to auto-clear saves: {ex}"); } } } }