Last active
April 29, 2025 21:48
-
-
Save maoyeedy/48745760573afe5ceadc068fc3a37ecb to your computer and use it in GitHub Desktop.
[Unity] Autosave the modified scenes when exiting playmode.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if UNITY_EDITOR | |
using UnityEditor; | |
using UnityEditor.SceneManagement; | |
using UnityEngine.SceneManagement; | |
namespace Project.Editor | |
{ | |
/// <summary> | |
/// Autosave the modified scenes when exiting playmode. | |
/// </summary> | |
[InitializeOnLoad] | |
public class AutoSaveFeature | |
{ | |
public static bool AutoSaveEnabled = true; // Set to false to disable auto-save | |
static AutoSaveFeature() | |
{ | |
EditorApplication.playModeStateChanged += AutoSaveWhenExitingPlaymode; | |
} | |
private static void AutoSaveWhenExitingPlaymode(PlayModeStateChange stateChange) | |
{ | |
if (!AutoSaveEnabled) return; | |
if (stateChange == PlayModeStateChange.ExitingPlayMode) | |
{ | |
EditorApplication.delayCall += SaveScenes; | |
} | |
} | |
private static void SaveScenes() | |
{ | |
for (var i = 0; i < SceneManager.sceneCount; i++) | |
{ | |
var scene = SceneManager.GetSceneAt(i); | |
if (scene.isDirty || scene.isLoaded) // isDirty means modified | |
{ | |
EditorSceneManager.SaveScene(scene); | |
} | |
} | |
AssetDatabase.SaveAssets(); | |
} | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment