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/