Last active
August 21, 2020 12:55
-
-
Save ChrisDirkis/b04aba21982d123889d7de478fea39b9 to your computer and use it in GitHub Desktop.
AutoSave script
This file contains 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
using System.Linq; | |
using UnityEditor; | |
using UnityEditor.SceneManagement; | |
using UnityEngine; | |
using UnityEngine.SceneManagement; | |
// Probably best to compile this to a DLL, or put in a folder with an | |
// assmebly definition set to editor only. Otherwise, put in an | |
// Editor folder inside your project. | |
namespace ChrisDirkis.Utility.Editor { | |
internal static class AutoSave { | |
[InitializeOnLoadMethod] | |
private static void RegisterAutoSaveCallback() { | |
LastAutoSave = EditorApplication.timeSinceStartup; | |
EditorApplication.update += AutoSaveCallback; | |
EditorApplication.playModeStateChanged += OnPlayModeStateChanged; | |
} | |
private const double TimeBetweenSaves = 5 * 60; | |
private static double LastAutoSave; | |
private static void AutoSaveCallback() { | |
if (!EditorApplication.isPlayingOrWillChangePlaymode && LastAutoSave + TimeBetweenSaves < EditorApplication.timeSinceStartup) { | |
LastAutoSave = EditorApplication.timeSinceStartup; | |
Save(); | |
} | |
} | |
private static void OnPlayModeStateChanged(PlayModeStateChange stateChange) { | |
if (stateChange == PlayModeStateChange.ExitingEditMode) { | |
Save(); | |
} | |
} | |
private static void Save() { | |
AssetDatabase.SaveAssets(); | |
Debug.Log("Saved assets"); | |
var dirtyScenes = Enumerable.Range(0, SceneManager.sceneCount) | |
.Select(SceneManager.GetSceneAt) | |
.Where(s => s.isLoaded && s.isDirty) | |
.ToList(); | |
EditorSceneManager.SaveOpenScenes(); | |
if (dirtyScenes.Count > 0) { | |
Debug.Log($"Saved scenes: {string.Join(", ", dirtyScenes.Select(s => s.name))}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment