停止Unity在运行时脚本修改重新编译的情况
nity3D有一个叫做”live recompile”的功能,即在编辑器处于播放状态时修改脚本代码或替换托管dll等操作时,当场触发重新编译生成项目脚本assembly,并会进行重新加载操作,然而,这个功能很多时候并不能保证重加载后的代码逻辑依然能正常运行,轻则报错,重则卡死。经过博主测试发现,Unity在重加载assembly后,会清空类实例部分成员变量的值(如在Awake中new出的数组对象等),且不负责还原。
使用以下脚本可以让Unity在代码修改时不重新编译,而是显示一个锁,在停止运行时才重新编译
// Copyright Cape Guy Ltd. 2018. http://capeguy.co.uk. // Provided under the terms of the MIT license - // http://opensource.org/licenses/MIT. Cape Guy accepts // no responsibility for any damages, financial or otherwise, // incurred as a result of using this code. using UnityEditor; using UnityEngine; /// <summary> /// Prevents script compilation and reload while in play mode. /// The editor will show a the spinning reload icon if there are unapplied changes but will not actually /// apply them until playmode is exited. /// Note: Script compile errors will not be shown while in play mode. /// Derived from the instructions here: /// https://support.unity3d.com/hc/en-us/articles/210452343-How-to-stop-automatic-assembly-compilation-from-script /// </summary> [InitializeOnLoad] public class DisableScripReloadInPlayMode { static DisableScripReloadInPlayMode() { EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } static void OnPlayModeStateChanged(PlayModeStateChange stateChange) { switch (stateChange) { case (PlayModeStateChange.EnteredPlayMode): { EditorApplication.LockReloadAssemblies(); Debug.Log ("Assembly Reload locked as entering play mode"); break; } case (PlayModeStateChange.ExitingPlayMode): { Debug.Log ("Assembly Reload unlocked as exiting play mode"); EditorApplication.UnlockReloadAssemblies(); break; } } } }
相关参考:https://answers.unity.com/questions/286571/can-i-disable-live-recompile.html
Unity2018已经可以自行设置
最完美的方案:https://capeguy.dev/2018/06/disabling-assembly-reload-while-in-play-mode/