A script to commit all changes before your game starts playing...

By mistake I introduced an infinte loop in my script… this forced me to kill Unity on the Windows Taks Manager, which obviously made me loose hours of changes.

After some research… and accordind to Unity’s manual, the following script will save all unsaved changes before playing my game:

using UnityEditor;
using UnityEngine;

public class menu : MonoBehaviour {

   [MenuItem("Edit/Safe Play")]
   public static void SafePlay(){
      AssetDatabase.SaveAssets();
      EditorApplication.isPlaying = true;
   }

}

However it must to be executed form the Edit menu. I want it to be exectued directly when I click the PLAY button (just below the main menu)… is that posible???.. if so… how???

SOLVED thanks to BoredMormon

Here is the code… enjoy!

using UnityEditor;
using UnityEngine;

public class menu : MonoBehaviour {

   [InitializeOnLoad]
   public class EditorPlayMode{

     static EditorPlayMode(){
         EditorApplication.playmodeStateChanged = PlayModeChanged;
     }
     private static void PlayModeChanged(){
        if(!EditorApplication.isPlaying){
           Debug.Log("saving...");
           AssetDatabase.SaveAssets();
           EditorApplication.SaveScene();
        }
     }

   }

}

The function is also called when you hit “Play” to stop the game, but I can live with that!