小工具知识网

当前位置: 首页 > 行业知识 > [unity] xLua 热更新 【个人复习笔记/有不足之处欢迎斧正/侵删】

行业知识

[unity] xLua 热更新 【个人复习笔记/有不足之处欢迎斧正/侵删】

2026-11-18 23:20:14 来源:互联网转载

 lua解析器

void Start()    {        //Lua解析器 能够让我们在Unity中执行Lua        //一般情况下 保持它的唯一性        LuaEnv env = new LuaEnv();        //执行Lua语言        env.DoString("print('你好世界')");        //执行一个Lua脚本 Lua知识点 :多脚本执行 require        //默认寻找脚本的路径 是在 Resources下 并且 因为在这里        //估计是通过 Resources.Load去加载Lua脚本  txt bytes等等        //所以Lua脚本 后缀要加一个txt        env.DoString("require('Main')");        //帮助我们清除Lua中我们没有手动释放的对象 垃圾回收        //帧更新中定时执行 或者 切场景时执行        env.Tick();        //销毁Lua解析器         env.Dispose();    }

文件加载重定向

env.AddLoader(MyCustomLoader);private byte[] MyCustomLoader(ref string filePath){    return null;}

解析器管理器

Lua���理器:

()

提供 lua解析器,保证解析器的唯一性-->使用单例模式

(Lua脚本会放到AB包中,最终通过加载AB包再加载其中的lua脚本资源来执行,但是AB包中如果要加载文本,后缀有一定的限制,.lua不能被识别)

()

从AB包加载文件:

    private byte[] MyCustomABLoader(ref string filePath)    {        //Debug.Log("进入AB包加载 重定向函数");        //从AB包中加载lua文件        //加载AB包        //string path = Application.streamingAssetsPath + "/lua";        //AssetBundle ab = AssetBundle.LoadFromFile(path);        //加载Lua文件 返回        //TextAsset tx = ab.LoadAsset(filePath + ".lua");        //加载Lua文件 byte数组        //return tx.bytes;        //通过我们的AB包管理器 加载的lua脚本资源        TextAsset lua = ABMgr.GetInstance().LoadRes("lua", filePath + ".lua");        if (lua != null)            return lua.bytes;        else            Debug.Log("MyCustomABLoader重定向失败,文件名为:" + filePath);        return null;    }

(Lua脚本会放在AB包 最终会通过加载AB包再加载其中的Lua脚本资源 来执行)

获取全局变量

只要在xlua中执行lua程序,都会自动进入重定向文件找

Lua代码

testNumber = 1testBool = truetestFloat = 1.2testString = "123"

C#代码

        //使用lua解析器luaenv中的 Global属性 (利用大G表)        int i = LuaMgr.GetInstance().Global.Get("testNumber");        Debug.Log("testNumber:" + i);        i = 10;        //改值        LuaMgr.GetInstance().Global.Set("testNumber", 55);        //值拷贝 不会影响原来Lua中的值        int i2 = LuaMgr.GetInstance().Global.Get("testNumber");        Debug.Log("testNumber_i2:" + i2);        bool b = LuaMgr.GetInstance().Global.Get("testBool");        Debug.Log("testBool:" + b);        float f = LuaMgr.GetInstance().Global.Get("testFloat");        Debug.Log("testFloat:" + f);        double d = LuaMgr.GetInstance().Global.Get("testFloat");        Debug.Log("testFloat_double:" + d);        string s = LuaMgr.GetInstance().Global.Get("testString");        Debug.Log("testString:" + s);

不能直接得到lua代码中的本地变量(local)

获取全局函数

lua代码:

--无参无返回testFun = function()print("无参无返回")end--有参有返回testFun2 = function(a)print("有参有返回")return a + 1end--多返回testFun3 = function(a)print("多返回值")return 1, 2, false, "123", aend--变长参数testFun4 = function(a, ...)print("变长参数")print(a)arg = {...}for k,v in pairs(arg) doprint(k,v)endend

c#代码:

c#去存函数-->使用委托

//无参无返回的获取        //委托        CustomCall call = LuaMgr.GetInstance().Global.Get("testFun");        call();        //Unity自带委托        UnityAction ua = LuaMgr.GetInstance().Global.Get("testFun");        ua();        //C#提供的委托        Action ac = LuaMgr.GetInstance().Global.Get("testFun");        ac();        //Xlua提供的一种 获取函数的方式 少用        //需要引用xlua        LuaFunction lf = LuaMgr.GetInstance().Global.Get("testFun");        lf.Call();        //有参有返回        CustomCall2 call2 = LuaMgr.GetInstance().Global.Get("testFun2");        Debug.Log("有参有返回:" + call2(10));        //C#自带的泛型委托 方便我们使用        Func sFun = LuaMgr.GetInstance().Global.Get("testFun2");        Debug.Log("有参有返回:" + sFun(20));        //Xlua提供的        LuaFunction lf2 = LuaMgr.GetInstance().Global.Get("testFun2");        Debug.Log("有参有返回:" + lf2.Call(30)[0]);        //多返回值        //使用 out 和 ref 来接收        CustomCall3 call3 = LuaMgr.GetInstance().Global.Get("testFun3");        int b;        bool c;        string d;        int e;        Debug.Log("第一个返回值:" + call3(100, out b, out c, out d, out e));        Debug.Log(b + "_" + c + "_" + d + "_" + e);        CustomCall4 call4 = LuaMgr.GetInstance().Global.Get("testFun3");        int b1 = 0;        bool c1 = true;        string d1 = "";        int e1 = 0;        Debug.Log("第一个返回值:" + call4(200, ref b1, ref c1, ref d1, ref e1));        Debug.Log(b1 + "_" + c1 + "_" + d1 + "_" + e1);        //Xlua        LuaFunction lf3 = LuaMgr.GetInstance().Global.Get("testFun3");        object[] objs = lf3.Call(1000);        for( int i = 0; i  

自定义的委托需要在c#脚本中添加特性,并在unity的xlua中生成code

//无参无返回值的委托public delegate void CustomCall();//有参有返回 的委托//该特性是在XLua命名空间中的//加了过后 要在编辑器里 生成 Lua代码[CSharpCallLua]public delegate int CustomCall2(int a);[CSharpCallLua]public delegate int CustomCall3(int a, out int b, out bool c, out string d, out int e);[CSharpCallLua]public delegate int CustomCall4(int a, ref int b, ref bool c, ref string d, ref int e);[CSharpCallLua]public delegate void CustomCall5(string a, params int[] args);

表(Table)映射 List 和 Dictionary

Lua代码:

--ListtestList = {1,2,3,4,5,6}testList2 = {"123", "123", true, 1, 1.2}--DictionarytestDic = {["1"] = 1,["2"] = 2,["3"] = 3,["4"] = 4}testDic2 = {["1"] = 1,[true] = 1,[false] = true,["123"] = false}

C#代码:

//同一类型List        List list = LuaMgr.GetInstance().Global.Get("testList");        Debug.Log("*******************List************************");        for ( int i = 0; i  10 then--停止协程和C#当中一样mono:StopCoroutine(b)endendend

不能直接将 lua函数传入到开启协程中,要利用xlua提供的一个工具表

--一定是要通过require调用之后 才能用util = require("xlua.util")

如果要把lua函数当做协程函数传入,必须先调用xlua.util中的cs_generator(lua函数)

b = mono:StartCoroutine(util.cs_generator(fun))

调用泛型函数方法

lua中不支持没有约束的泛型函数,也不支持有约束但是没有参数的泛型函数,还不支持非class的约束(用接口约束的)

如何让上面不支持使用的泛型函数变得能用?

答:得到通用函数,设置泛型类型再使用。

       xlua.get_generic_method(类, "函数名")

local testFun2 = xlua.get_generic_method(CS.Lesson12, "TestFun2")local testFun2_R = testFun2(CS.System.Int32)--调用--成员方法  第一个参数 传调用函数的对象--静态方法 不用传testFun2_R(obj, 1)

但是有一定的使用限制

Mono打包:这种方式支持使用

il2cpp打包 :如果泛型参数是引用类型才可以使用;如果泛型参数是值类型,除非C#那边已经调用过了,同类型的泛型参数 lua中才能够被使用

热补丁

lua当中热补丁代码固定写法:xlua.hotfix(类, "函数名", lua函数)

--成员函数 第一个参数 selfxlua.hotfix(CS.HotfixMain, "Add", function(self, a, b)return a + bend)--静态函数 不用传第一个参数xlua.hotfix(CS.HotfixMain, "Speak", function(a)print(a)end)

注意:直接写好代码运 是会报错的,必须做4个非常重要的操作

1.加特性

2.加宏 (第一次开发热补丁需要加)Project Settings->Player->Scripting Define Symbols

3.生成代码

4.hotfix 注入  (注入时可能报错,提示要引入Tools)

只要我们修改了热补丁类的代码,就需要重新执行hotfix 注入(需要重新点击 注入)

多函数替换

xlua.hotfix(类, {函数名 = 函数, 函数名 = 函数....})

xlua.hotfix(CS.HotfixMain, {Update = function(self)print(os.time())end,Add = function(self, a, b )return a + bend,Speak = function(a)print(a)end})

构造函数-热补丁固定写法        [".ctor"]

和别的函数不同,构造函数不是替换,而是先调用原逻辑,再调用lua逻辑

析构函数固定写法 Finalize

xlua.hotfix(CS.HotfixTest, {[".ctor"] = function()end,Speak = function(self,a)end,--析构函数Finalize = function()end})

协程函数替换

要在lua中配合C#协程函数,必须使用

util = require("xlua.util")

如果是为打了Hotfix特性的C#类新加了函数内容,不能只注入 ,必须要先生成代码再注入,不然注入会报错

xlua.hotfix(CS.HotfixMain, {TestCoroutine = function(self)--返回一个正儿八经的 xlua处理过的lua协程函数return util.cs_generator(function()while true docoroutine.yield(CS.UnityEngine.WaitForSeconds(1))print("Lua打补丁后的协程函数")endend)end})

属性和索引器替换

属性进行热补丁重定向:

set_属性名 是设置属性 的方法

get_属性名 是得到属性 的方法

xlua.hotfix(CS.HotfixMain, {set_Age = function(self, v)print("Lua重定向的属性"..v)end,get_Age = function(self)return 10;end})

索引器进行热补丁重定向:

set_Item 通说索引器设置

get_Item 通过索引器获取

xlua.hotfix(CS.HotfixMain, {set_Age = function(self, v)print("Lua重定向的属性"..v)end,get_Age = function(self)return 101;end,set_Item = function(self, index, v )end,get_Item = function(self, index)return 666end})

事件的替换

add_事件名 代表着时间加操作

remove_事件名 减操作

xlua.hotfix(CS.HotfixMain, {add_myEvent = function(self, del)print(del)end,remove_myEvent = function(self, del )print(del)end})

注意:重定向后,如果使用lua使用C#事件的方法去添加,在事件加减的重定向lua函数中,不要把传入的委托往事件里存,会***循环(会把传入的函数存在lua中)-> self:myEvent("+", del)

泛型类的替换

泛型类中的T是可以变化,但是lua中的替换 要一个类型一个类型的来

xlua.hotfix(CS.HotfixTest2(CS.System.String), {Test = function(self, str)end})xlua.hotfix(CS.HotfixTest2(CS.System.Int32), {Test = function(self, str)end})

别忘了成员方法第一个参数是self

上一篇:微拼团系统搭建指南,微擎安装攻略,轻松开启团购之旅!

下一篇:服务器主机怎么制造?