Search Unity

A Simple Save On Play Script

Discussion in 'Scripting' started by jeffweber, Jan 27, 2012.

  1. jeffweber

    jeffweber

    Joined:
    Dec 17, 2009
    Posts:
    616
    I use Visual Studio a lot and one of the things I came to rely on is the project saving everytime I run it.

    I wanted the same for Unity scenes so I created a simple little script.

    To use it:

    1. Add the script to your scene.

    2. Go to Edit-->Project Settings-->Script Execution Order and set your "SaveOnPlay" script to execute first. (This is so it saves before any of your code runs that may modify the scene programmatically.)

    Note: You'll want to remove/disable this script prior to releasing you game.

    That's it. Let me know what you think.

    The script:

    Code (csharp):
    1. using UnityEngine;
    2. using UnityEditor;
    3. using System.Collections;
    4.  
    5. public class SaveOnPlay : MonoBehaviour {
    6.  
    7.     void Awake()
    8.     {
    9.         EditorApplication.playmodeStateChanged += HandlePlayModeStateChanged;
    10.     }
    11.    
    12.     void HandlePlayModeStateChanged()
    13.     {
    14.         EditorApplication.SaveScene();
    15.         EditorApplication.playmodeStateChanged -= HandlePlayModeStateChanged; //don't fire event on exiting play
    16.        
    17.     }
    18. }
     
    WheresMommy and ocimum like this.
  2. LandonB

    LandonB

    Joined:
    Jul 11, 2012
    Posts:
    1
    Dude, thank you so much. I too have been spoiled by save-on-run programs like MVS and I have lost a lot of work in unity because of it crashing. This is awesome.
     
  3. jackmott

    jackmott

    Joined:
    Jan 5, 2014
    Posts:
    167
    Thank you lord!
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,619
    Rather than manually removing it from builds, you could stick it in a #if block.
    Code (csharp):
    1. #if UNITY_EDITOR
    2.     // Editor specific stuff in here
    3. #endif
     
  5. ocimum

    ocimum

    Joined:
    Apr 19, 2015
    Posts:
    12
    Nice snippet! Thanks a lot!