在游戏开发阶段中,经常需要小修小改,Unity提供了很方便的Scene窗口,让开发者的修改马上生效,而不需要重新启动游戏。
那么代码需要怎么样才能做到一修改就马上生效,并且不需要重启游戏呢?
下面结合Slua来说一下代码自动更新的方案(我使用的版本是slua-1.3.2,较旧)
思路:
- 获取Lua加载过哪些文件,记录下这些文件的文件名、全路径和最后修改时间
- 定时检测文件的最后修改时间,如果比记录的最后修改时间还要大,则表示在加载后发生过修改,然后重新加载它
代码:
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SLua;
using System;
namespace XS
{
public class ImmediateLuaScript : MonoBehaviour
{
public class ScriptInfo
{
public string strFileName;
public string strFileFullPath;
public System.DateTime dtLastWrite;
}
List<ScriptInfo> m_loadedScripts = new List<ScriptInfo>();
int m_nNextScriptIndex = 0;
private static ImmediateLuaScript _Instance;
public static ImmediateLuaScript Instance
{
get
{
if (_Instance == null)
{
GameObject resMgr = GameObject.Find("_ImmediateLuaScript");
if (resMgr == null)
{
resMgr = new GameObject("_ImmediateLuaScript");
GameObject.DontDestroyOnLoad(resMgr);
}
_Instance = resMgr.AddComponent<ImmediateLuaScript>();
}
return _Instance;
}
}
#if UNITY_EDITOR
// 可以通过外部控制ImmediateLuaScriptInEditor,使自动更新暂停或恢复
public static bool ImmediateLuaScriptInEditor = true;
// 每帧检查文件数,可根据文件数量成正比
public static int CheckFilesOnce = 5;
ScriptInfo getScriptInfo(string strFileFullPath)
{
foreach (ScriptInfo info in m_loadedScripts)
{
if(info.strFileFullPath == strFileFullPath)
{
return info;
}
}
return null;
}
ScriptInfo getOrCreateScriptInfo(string strFileName, string strFileFullPath)
{
ScriptInfo info = getScriptInfo(strFileFullPath);
if (info != null) return info;
info = new ScriptInfo();
info.strFileName = strFileName;
info.strFileFullPath = strFileFullPath;
m_loadedScripts.Add(info);
return info;
}
ScriptInfo getNextScriptInfo()
{
if (m_nNextScriptIndex >= m_loadedScripts.Count)
{
m_nNextScriptIndex = 0;
return null;
}
return m_loadedScripts[m_nNextScriptIndex++];
}
string getFileFullPath(string strFileName)
{
string strFileFullPath;
do
{
// 这里的代码目录路径属于自定义
strFileFullPath = UnityEngine.Application.dataPath + "/../luaScript/" + strFileName + ".lua";
if (System.IO.File.Exists(strFileFullPath))
break;
} while (false);
return strFileFullPath;
}
public void SetImmediateLuaScript(string strFileName)
{
if (!ImmediateLuaScriptInEditor) return;
string strFileFullPath = getFileFullPath(strFileName);
FileInfo fileInfo = new FileInfo(strFileFullPath);
if(fileInfo.Exists)
{
ScriptInfo info = getOrCreateScriptInfo(strFileName, strFileFullPath);
info.dtLastWrite = fileInfo.LastWriteTime;
}
}
void checkScriptUpdate()
{
ScriptInfo info = getNextScriptInfo();
if (info == null) return;
FileInfo fileInfo = new FileInfo(info.strFileFullPath);
if (info.dtLastWrite < fileInfo.LastWriteTime)
{
info.dtLastWrite = fileInfo.LastWriteTime;
bool result = loadScriptFile(info.strFileName, info.strFileFullPath);
if(!result)
{
var L = LuaSvr.Instance.luaState.L;
string err = LuaDLL.lua_tostring(L, -1);
LuaDLL.lua_pop(L, 2);
throw new Exception(err);
}
}
}
void LateUpdate()
{
if (!ImmediateLuaScriptInEditor) return;
for(int i=0;i<CheckFilesOnce; i++)
{
checkScriptUpdate();
}
}
public static int newLoader(System.IntPtr L)
{
string fileName = LuaDLL.lua_tostring(L, 1);
Instance.SetImmediateLuaScript(fileName);
LuaObject.pushValue(L, true);
LuaDLL.lua_pushnil(L);
return 2;
}
// 注册Lua脚本loader
public void AddLuaLoaders(System.IntPtr L)
{
LuaState.pushcsfunction(L, newLoader);
int loaderFunc = LuaDLL.lua_gettop(L);
LuaDLL.lua_getglobal(L, "package");
#if LUA_5_3
LuaDLL.lua_getfield(L, -1, "searchers");
#else
LuaDLL.lua_getfield(L, -1, "loaders");
#endif
int loaderTable = LuaDLL.lua_gettop(L);
// Shift table elements right
for (int e = LuaDLL.lua_rawlen(L, loaderTable) + 1; e > 2; e--)
{
LuaDLL.lua_rawgeti(L, loaderTable, e - 1);
LuaDLL.lua_rawseti(L, loaderTable, e);
}
LuaDLL.lua_pushvalue(L, loaderFunc);
LuaDLL.lua_rawseti(L, loaderTable, 2);
LuaDLL.lua_settop(L, 0);
}
// 加载lua文件
bool loadScriptFile(string strFileName, string strFileFullPath)
{
FileStream fs = new FileStream(strFileFullPath, FileMode.Open);
long size = fs.Length;
byte[] bytes = new byte[size];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
bytes = LuaState.CleanUTF8Bom(bytes);
var L = LuaSvr.Instance.luaState.L;
if (bytes != null)
{
var nOldTop = LuaDLL.lua_gettop(L);
var err = LuaDLL.luaL_loadbuffer(L, bytes, bytes.Length, "@" + strFileFullPath);
if (err != 0)
{
string errstr = LuaDLL.lua_tostring(L, -1);
LuaDLL.lua_pop(L, 1);
LuaObject.error(L, errstr);
return false;
}
err = LuaDLL.lua_pcall(L, 0, 0, 0);
if (err != 0)
{
string errstr = LuaDLL.lua_tostring(L, -1);
LuaDLL.lua_pop(L, 1);
LuaObject.error(L, errstr);
return false;
}
LuaDLL.lua_settop(L, nOldTop);
Debug.Log(" *** Reload Lua File Successful : " + strFileName);
return true;
}
LuaObject.error(L, "Can't find {0}", strFileFullPath);
return false;
}
#endif
}
}
使用:
在Slua启动时,在任何未加载Lua脚本前调用
ImmediateLuaScript.Instance.AddLuaLoaders(luaState.L);
来完成注册
注意事项:
- 热更新Lua代码只是针对具体文件依次执行luaL_loadbuffer和lua_pcall,并不能更新代码中的闭包
- 代码中的局部变量会丢失,所以需要在代码书写时注意局部变量的保存(这里涉及Lua框架设计,如setfenv、module、_ENV,甚至面向对象)
- 可以通过增大CheckFilesOnce来加快检测速度,但是这样会影响到游戏运行时的性能
- 每次更新代码后会在后台输出 “ *** Reload Lua File Successful : FileName ”