美文网首页奇哥Unity
Unity开发时自动热更新Lua代码

Unity开发时自动热更新Lua代码

作者: 慢慢来比较快_ | 来源:发表于2019-08-09 11:13 被阅读0次

在游戏开发阶段中,经常需要小修小改,Unity提供了很方便的Scene窗口,让开发者的修改马上生效,而不需要重新启动游戏。
那么代码需要怎么样才能做到一修改就马上生效,并且不需要重启游戏呢?

下面结合Slua来说一下代码自动更新的方案(我使用的版本是slua-1.3.2,较旧)

思路:

  1. 获取Lua加载过哪些文件,记录下这些文件的文件名、全路径和最后修改时间
  2. 定时检测文件的最后修改时间,如果比记录的最后修改时间还要大,则表示在加载后发生过修改,然后重新加载它
代码:
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);

来完成注册

注意事项:

  1. 热更新Lua代码只是针对具体文件依次执行luaL_loadbuffer和lua_pcall,并不能更新代码中的闭包
  2. 代码中的局部变量会丢失,所以需要在代码书写时注意局部变量的保存(这里涉及Lua框架设计,如setfenv、module、_ENV,甚至面向对象)
  3. 可以通过增大CheckFilesOnce来加快检测速度,但是这样会影响到游戏运行时的性能
  4. 每次更新代码后会在后台输出 “ *** Reload Lua File Successful : FileName ”

相关文章

  • Unity开发时自动热更新Lua代码

    在游戏开发阶段中,经常需要小修小改,Unity提供了很方便的Scene窗口,让开发者的修改马上生效,而不需要重新启...

  • LuaFramework

    ULUA简介: ULUA:Unity AssetStore 中一款热更新插件Lua Framework 的简称,2...

  • Unity--Lua热更新

    一、什么是热更新? 一般游戏上线后,玩家下载了第一个版本,在运营的过程中,会不定时的发布新的版本,如果不使用热更新...

  • [Unity]基于IL代码注入的Lua补丁方案

    本分享的想法源于看了这篇分享由于在对Unity项目后期进行lua热更新方案实施, 我也不想造成源代码的修改, 故在...

  • unity真机快速开发调试构思

    移动开发特别是游戏开发领域,可热更新基本是标配。我们的项目是采用Unity同时是采用第三方插件绑定c#与lua实现...

  • 如何评价C#热更框架huatuo?

    为什么这么NB?huatuo革命Unity热更新 最近huatuo(华佗)热更新解决方案火爆了unity开发圈,起...

  • Unity 热更新 之 如何使用AST转换 C# -> Lua

    本文转自Unity Connect博主 郡墙 本篇主要论述 如何将 C# 代码自动转换为 Lua 代码的解决方案...

  • c#和lua的交互的优化

    lua是目前最强大的unity热更新方案,毕竟这是唯一可以支持ios热更新的办法。然而作为一个重度ulua用户,我...

  • unity_lua热更新_语录

    ** lua 调用unity方法中,如果是静态方法要用 "." 如果是非静态方法要用 ":"** 1.lua中字符...

  • lua之table与#与nil凌乱组合

    写在前面 lua是在unity3d前端开发中经常被用到的语言,因为其轻量和热更新的特性深受欢迎,招聘信息中也经常会...

网友评论

    本文标题:Unity开发时自动热更新Lua代码

    本文链接:https://www.haomeiwen.com/subject/xbucjctx.html