修改日期 | 修改人 | 备注 |
2021-10-25 13:51:04[当前版本] | 胡金旗 | 创建版本 |
2021-10-23 17:41:13 | 胡金旗 | 创建版本 |
Unity3D有一个叫做”live recompile”的功能,即在编辑器处于播放状态时修改脚本代码或替换托管dll等操作时,当场触发重新编译生成项目脚本assembly,并会进行重新加载操作,然而,这个功能很多时候并不能保证重加载后的代码逻辑依然能正常运行,轻则报错,重则卡死。经过博主测试发现,Unity在重加载assembly后,会清空类实例部分成员变量的值(如在Awake中new出的数组对象等),且不负责还原。最终,为了避免由于此导致的问题,采取了一种回避的手段:通过Editor脚本方式检测是否在播放状态时触发了脚本编译,是的话立即停止播放,代码如下:
// 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;
[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;
}
}
}
}
将上面代码创建脚本,直接放到unity工程中即可。