[Unity] Auto-save scene on play (to prevent work-loss on crash)

edited in Tutorials
Hi!

For those of you who use Unity, I am sure you have encountered the frustrations of having Unity crash on you - due to something you did, or due to a bug in Unity. Either way, if you have forgotten to save your scene in a while, you may have lost a significant amount of work. This script will help minimize the risk a bit by auto-saving your scene when you press play (assuming you play-test a lot like me, you will rarely lose any work again). Simply add it to an object that is in all your scenes:

#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;


[InitializeOnLoad]
public class AutosaveOnRun: ScriptableObject
{
	static AutosaveOnRun()
	{
		EditorApplication.playmodeStateChanged = () =>
		{
			if(EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
			{
				Debug.Log("Auto-Saving scene before entering Play mode: " + EditorApplication.currentScene);
				
				EditorApplication.SaveScene();
				EditorApplication.SaveAssets();
			}
		};
	}
}
#endif
Thanked by 1hermantulleken

Comments

  • lol.
    Me and @tbulford were saying the other day that we wish unity would do this... and now it does
    THANK YOU
  • Oh nice.

    You should consider releasing this one the unity asset store as a free script.
  • edited
    @tbulfrod I actually copied from a Unity answers... answer. Just added the #if so that it doesn't compile in actual builds (as it can't and will give an error). I couldn't not share it with you guys. I nearly scratched my own eyeballs out when I lost some work. again. So I opted to instead keep my eyes, and look for a solution instead.
  • Wow @Denzil

    Thank for this.
Sign In or Register to comment.