【unity】自动保存项目

原文来自于:http://wiki.unity3d.com/index.php?title=AutoSave#C.23_-_AutoSave.cs

用于:在编写项目时,unity 的Bug导致强制退出,来不及保存

点击查看代码
using UnityEngine;
using UnityEditor;
using System;
public class AutoSave : EditorWindow
{
    private bool autoSaveScene = true;
    private bool showMessage = true;
    private bool isStarted = false;
    private int intervalScene;
    private DateTime lastSaveTimeScene = DateTime.Now;

    private string projectPath = Application.dataPath;
    private string scenePath;

    [MenuItem("Window/AutoSave")]
    static void Init()
    {
        AutoSave saveWindow = (AutoSave)EditorWindow.GetWindow(typeof(AutoSave));
        saveWindow.Show();
    }

    void OnGUI()
    {
        GUILayout.Label("Info:", EditorStyles.boldLabel);
        EditorGUILayout.LabelField("Saving to:", "" + projectPath);
        EditorGUILayout.LabelField("Saving scene:", "" + scenePath);
        GUILayout.Label("Options:", EditorStyles.boldLabel);
        autoSaveScene = EditorGUILayout.BeginToggleGroup("Auto save", autoSaveScene);
        intervalScene = EditorGUILayout.IntSlider("Interval (minutes)", intervalScene, 1, 10);
        if (isStarted)
        {
            EditorGUILayout.LabelField("Last save:", "" + lastSaveTimeScene);
        }
        EditorGUILayout.EndToggleGroup();
        showMessage = EditorGUILayout.BeginToggleGroup("Show Message", showMessage);
        EditorGUILayout.EndToggleGroup();
    }


    void Update()
    {
        scenePath = EditorApplication.currentScene;
        if (autoSaveScene)
        {
            if (DateTime.Now.Minute >= (lastSaveTimeScene.Minute + intervalScene) || DateTime.Now.Minute == 59 && DateTime.Now.Second == 59)
            {
                saveScene();
            }
        }
        else
        {
            isStarted = false;
        }

    }

    void saveScene()
    {
        EditorApplication.SaveScene(scenePath);
        lastSaveTimeScene = DateTime.Now;
        isStarted = true;
        if (showMessage)
        {
            Debug.Log("AutoSave saved: " + scenePath + " on " + lastSaveTimeScene);
        }
        AutoSave repaintSaveWindow = (AutoSave)EditorWindow.GetWindow(typeof(AutoSave));
        repaintSaveWindow.Repaint();
    }
}

脚本放在Assets/Editor文件夹中,Auto Save在激活状态下有效,不要直接关闭插件窗口,可以把插件窗口拖到hierachy右侧
image

posted @ 2025-08-05 11:21  EanoJiang  阅读(53)  评论(0)    收藏  举报