Unity自动保存场景

1,根据InitializeOnLoad属性,放在类前,声明静态构造函数,即可在编辑器启动时调用该静态构造函数
2,UnityEditor.EditorApplication.update委托可以在编辑器下实现运行时的Update
3, EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());保存场景
实现:

using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System;

[InitializeOnLoad]
public class XPAutoSave 
{

    public static Scene nowScene;
    public static DateTime lastSaveTime = DateTime.Now;
    static XPAutoSave()
    {
        lastSaveTime = DateTime.Now;
        EditorApplication.update += EditorUpdate;
    }
    ~XPAutoSave()
    {
        EditorApplication.update -= EditorUpdate;
    }
    static void EditorUpdate()
    {
        if (AutoSaveWindow.autoSaveScene)
        {
            double seconds = (DateTime.Now - lastSaveTime).TotalSeconds;
            if (seconds > AutoSaveWindow.intervalTime)
            {
                saveScene();
                lastSaveTime = DateTime.Now;
            }
        }
    }

        static void saveScene()
        {
            if (nowScene.isDirty)
            {
                nowScene = EditorSceneManager.GetActiveScene();
                EditorSceneManager.SaveScene(nowScene);
                if (AutoSaveWindow.showMessage)
                {
                    Debug.Log("自动保存场景: " + nowScene.path + "  " + lastSaveTime);
                }
            }

        }
}
using UnityEditor;

public class AutoSaveWindow : EditorWindow
{
    public static bool autoSaveScene = true;
    public static bool showMessage = true;
    public static int intervalTime = 30;
    [MenuItem("XP/自动保存面板")]
    static void Init()
    {
        EditorWindow saveWindow = EditorWindow.GetWindow(typeof(AutoSaveWindow));
        saveWindow.minSize = new Vector2(200, 200);
        saveWindow.Show();
    }
    void OnGUI()
    {
        GUILayout.Label("信息", EditorStyles.boldLabel);
        EditorGUILayout.LabelField("保存场景:", "" + XPAutoSave.nowScene.path);
        GUILayout.Label("选择", EditorStyles.boldLabel);
        autoSaveScene = EditorGUILayout.BeginToggleGroup("自动保存", autoSaveScene);
        intervalTime = EditorGUILayout.IntField("时间间隔(秒)", intervalTime);
        EditorGUILayout.EndToggleGroup();
        showMessage = EditorGUILayout.BeginToggleGroup("显示消息", showMessage);
        EditorGUILayout.EndToggleGroup();
    }
}

将放到Editor文件下即可,
通过菜单栏(XP/自动保存面板)可以设置自动保存的时间和是否自动保存
在这里插入图片描述
Unity自动保存场景_第1张图片

你可能感兴趣的:(UnityEditor,unity)