原文來自於:http://wiki.unity3d.com/index.php?title=AutoSave#C.23_-_AutoSave.cs (奮鬥的菜鳥_1029633680)php
不少時候,在編寫項目時,碰見unity 的Buge致使強制退出,這時根原本不及保存hierarchy視圖中的東西,這是一件很糟糕的事情,因此在今天看資料時,有幸的看到了這篇自動保存項目場景的源碼。非常不錯。ide
源碼以下:spa
1 using UnityEngine; 2 using UnityEditor; 3 using System; 4 5 public class AutoSave : EditorWindow 6 { 7 8 private bool autoSaveScene = true; 9 private bool showMessage = true; 10 private bool isStarted = false; 11 private int intervalScene; 12 private DateTime lastSaveTimeScene = DateTime.Now; 13 14 private string projectPath = Application.dataPath; 15 private string scenePath; 16 17 [MenuItem("Window/AutoSave")] 18 static void Init() 19 { 20 AutoSave saveWindow = (AutoSave)EditorWindow.GetWindow(typeof(AutoSave)); 21 saveWindow.Show(); 22 } 23 24 void OnGUI() 25 { 26 GUILayout.Label("Info:", EditorStyles.boldLabel); 27 EditorGUILayout.LabelField("Saving to:", "" + projectPath); 28 EditorGUILayout.LabelField("Saving scene:", "" + scenePath); 29 GUILayout.Label("Options:", EditorStyles.boldLabel); 30 autoSaveScene = EditorGUILayout.BeginToggleGroup("Auto save", autoSaveScene); 31 intervalScene = EditorGUILayout.IntSlider("Interval (minutes)", intervalScene, 1, 10); 32 if (isStarted) 33 { 34 EditorGUILayout.LabelField("Last save:", "" + lastSaveTimeScene); 35 } 36 EditorGUILayout.EndToggleGroup(); 37 showMessage = EditorGUILayout.BeginToggleGroup("Show Message", showMessage); 38 EditorGUILayout.EndToggleGroup(); 39 } 40 41 42 void Update() 43 { 44 scenePath = EditorApplication.currentScene; 45 if (autoSaveScene) 46 { 47 if (DateTime.Now.Minute >= (lastSaveTimeScene.Minute + intervalScene) || DateTime.Now.Minute == 59 && DateTime.Now.Second == 59) 48 { 49 saveScene(); 50 } 51 } 52 else 53 { 54 isStarted = false; 55 } 56 57 } 58 59 void saveScene() 60 { 61 EditorApplication.SaveScene(scenePath); 62 lastSaveTimeScene = DateTime.Now; 63 isStarted = true; 64 if (showMessage) 65 { 66 Debug.Log("AutoSave saved: " + scenePath + " on " + lastSaveTimeScene); 67 } 68 AutoSave repaintSaveWindow = (AutoSave)EditorWindow.GetWindow(typeof(AutoSave)); 69 repaintSaveWindow.Repaint(); 70 } 71 }
值得注意的是:建立好這個腳本後,放在Assets/Editor文件夾中,而後編輯的窗口再Window目錄下。3d
在激活狀態下,纔可有效。但願對你們有所幫助。code