Unity如何处理lua热重载?

lua热重载就是运行时修改代码不需要重新运行就可以生效的一种方案。首先先上方案链接:

https://github.com/asqbtcupid/lua_hotupdate

git上已经有人做出了现成的方案,拿来即用。

如果在Unity中使用需要检测lua文件的修改,通过以下代码进行:

using UnityEngine;
using UnityEditor;
public class LuaFastProcessor : AssetPostprocessor
{
    protected const string HOT_FIX_STR = "HU.Update()";
    public static void OnPostprocessAllAssets(string[] importedAsset, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        if (Application.isPlaying)
        {
            string path = Application.dataPath + "\\StreamingAssets\\scripts\\hotupdatelist.lua";
            StringBuilder sb = new StringBuilder();
            sb.Append("local FileNameList = {\n");
            for (int i = 0; i < importedAsset.Length; i++)
            {
                bool isLuaFile = importedAsset[i].EndsWith(".lua");
                if (isLuaFile)
                {
                    if (XLuaManager.Instance.LuaEnvIns != null)
                    {
                        sb.Append("\"");
                        string strName = importedAsset[i].Replace(".lua", "");
                        strName = strName.Substring(strName.LastIndexOf("/") + 1);
                        Debug.LogError(strName);
                        sb.Append(strName);
                        sb.Append("\",");
                    }
                }
            }

            sb.Append(@"
                    }
                    return FileNameList");
            File.WriteAllText(path,sb.ToString());
            if(XLuaManager.Instance.LuaEnvIns!=null)
                XLuaManager.Instance.LuaEnvIns.DoString(string.Format(HOT_FIX_STR));
        }
    }
}

我们通过继承AssetPostprocessor来监测lua文件修改。当修改的时候,我们找到哪些地方进行了修改,并写入到hotupdatelistt文件中。

最后在call一次lua中的luahotupdate脚本的Update方法,脚本可以从上面git链接下到。

这里我用了git中的支持lua5.3的脚本,记得在lua的入口调用一次 luahotupdate.Init()方法。

主要原理就是package.loaded中拿到已经加载的信息,然后找到并load新的脚本并进行table的replace,具体如何replace请参照git中的代码。