Skip to content

Instantly share code, notes, and snippets.

@dustingraham
Last active March 1, 2024 09:19
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dustingraham/3e5367a12acba1eb013cc35e187e3898 to your computer and use it in GitHub Desktop.
Save dustingraham/3e5367a12acba1eb013cc35e187e3898 to your computer and use it in GitHub Desktop.
Auto-Save open unity scenes when launching play mode, or every five minutes.
#if UNITY_EDITOR
using System;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
[InitializeOnLoad]
public class AutoSave
{
private static DateTime nextSaveTime;
// Static constructor that gets called when unity fires up.
static AutoSave()
{
EditorApplication.playModeStateChanged += (PlayModeStateChange state) => {
// If we're about to run the scene...
if (!EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isPlaying) return;
// Save the scene and the assets.
Debug.Log("Auto-saving all open scenes... " + state);
EditorSceneManager.SaveOpenScenes();
AssetDatabase.SaveAssets();
};
// Also, every five minutes.
nextSaveTime = DateTime.Now.AddMinutes(5);
EditorApplication.update += Update;
Debug.Log("Added callback.");
}
private static void Update()
{
if (nextSaveTime > DateTime.Now) return;
nextSaveTime = nextSaveTime.AddMinutes(5);
Debug.Log("AutoSave Scenes: "+DateTime.Now.ToShortTimeString());
EditorSceneManager.SaveOpenScenes();
AssetDatabase.SaveAssets();
}
}
#endif
@dustingraham
Copy link
Author

Updated to also save every five minutes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment