赞
踩
没有起因,只是想写点东西。
1、使用的Unity版本如图:
2、代码如下:
using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; [InitializeOnLoad] public class AutoSave { static AutoSave() { EditorApplication.playModeStateChanged += SaveOnPlay; } private static void SaveOnPlay(PlayModeStateChange state) { if(state==PlayModeStateChange.ExitingEditMode) { Debug.Log("Auto-saving ..."); EditorSceneManager.SaveOpenScenes(); AssetDatabase.SaveAssets(); } } }
3、稍作解释:
a、InitializeOnLoad 意思就是说当你的Unity初始化和重编译的时候顺带也初始化这个编辑器类。
b、一个静态方法,监听当play 模式发生改变的时候执行某个方法,此处执行的是SaveOnPlay方法。
c、SaveOnPlay方法中就是监听状态发生改变,改变成退出Edit模式的时候(不是退出Unity)执行场景保存和保存AssetData。
顺带看一下这个枚举:
namespace UnityEditor { // // 摘要: // Enumeration specifying a change in the Editor's play mode state. See Also: PauseState, // EditorApplication.playModeStateChanged, EditorApplication.isPlaying. public enum PlayModeStateChange { // // 摘要: // Occurs during the next update of the Editor application if it is in edit mode // and was previously in play mode. EnteredEditMode = 0, // // 摘要: // Occurs when exiting edit mode, before the Editor is in play mode. ExitingEditMode = 1, // // 摘要: // Occurs during the next update of the Editor application if it is in play mode // and was previously in edit mode. EnteredPlayMode = 2, // // 摘要: // Occurs when exiting play mode, before the Editor is in edit mode. ExitingPlayMode = 3 } }
说白了就是进入Editor模式、退出Editor模式、进入Play模式和退出Play模式。至于他们的顺序,我们可以试验验证下,代码如下:
using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; [InitializeOnLoad] public class AutoSave { static AutoSave() { EditorApplication.playModeStateChanged += SaveOnPlay; } private static void SaveOnPlay(PlayModeStateChange state) { if(state==PlayModeStateChange.ExitingEditMode) { Debug.Log("ExitingEditMode"); Debug.Log("Auto-saving ..."); EditorSceneManager.SaveOpenScenes(); AssetDatabase.SaveAssets(); } if (state == PlayModeStateChange.EnteredEditMode) { Debug.Log("EnteredEditMode"); } if (state == PlayModeStateChange.EnteredPlayMode) { Debug.Log("EnteredPlayMode"); } if (state == PlayModeStateChange.ExitingPlayMode) { Debug.Log("ExitingPlayMode"); } } }
结果如下,是不是跟我们预想的一样。(试验过程就是从Editor模式运行一下,然后关闭运行状态)并没有什么特别的事情。
最近如果闲,可能会出一系列这种。有兴趣的可以持续关注一下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。