使用XLua在Unity中获取lua全局变量和函数

1、Lua脚本

入口脚本

Lua 复制代码
print("OK")
--也会执行重定向
require("Test")

测试脚本

Lua 复制代码
print("TestScript")
testNum = 1
testBool = true
testFloat = 1.2
testStr = "123"

function testFun()
	print("无参无返回")
end

function testFun2(a)
	print("有参有返回")
	return a
end

2、C#脚本

(1)获取全局变量

cs 复制代码
public class L4 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //自己编写的Lua管理器
        //初始化管理器
        LuaMgr.GetInstance().Init();
        //执行Main脚本(调用了Test脚本)
        LuaMgr.GetInstance().DoLuaFile("Main");

        //得到全局变量(只是复制到C#,改不了)
        int i = LuaMgr.GetInstance().Global.Get<int>("testNum");
        print(i);
        //修改全局变量
        LuaMgr.GetInstance().Global.Set("testNum", 2);
        i = LuaMgr.GetInstance().Global.Get<int>("testNum");
        print(i);
    }
}

执行结果

(2)获取全局函数

cs 复制代码
using XLua;
public class L5 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        LuaMgr.GetInstance().Init();
        LuaMgr.GetInstance().DoLuaFile("Main");

        #region 无参无返回
        //第一种方法 通过 GetFunction方法获取(需要引用命名空间)
        LuaFunction function = LuaMgr.GetInstance().Global.Get<LuaFunction>("testFun");
        //调用 无参无返回
        function.Call();
        //执行完过后 
        function.Dispose();
        #endregion
    
        #region 有参有返回
        //第一种方式 通过luafunction 的 call来访问
        LuaFunction function2 = LuaMgr.GetInstance().Global.Get<LuaFunction>("testFun2");
        
        Debug.Log("有参有返回值 Call:" + function2.Call(10)[0]);
        #endregion
    }
}
相关推荐
王小义笔记35 分钟前
Postman如何流畅使用DeepSeek
开发语言·测试工具·lua·postman·deepseek
程序猿多布6 小时前
预定义委托(C# and Unity)
unity·c#
虾球xz9 小时前
游戏引擎学习第108天
学习·游戏引擎
虾球xz10 小时前
游戏引擎学习第112天
java·学习·游戏引擎
Edision_li16 小时前
DeepSeek教unity------Dotween
unity·游戏引擎
zfoo-framework17 小时前
Unity中NavMesh的使用 及其 导出给java服务端进行寻路
unity
程序猿多布17 小时前
数学函数(C#、Lua 、Unity)
unity·c#·lua
程序猿多布17 小时前
字符串操作总结(C# and Lua)
c#·lua
虾球xz19 小时前
游戏引擎学习第110天
数码相机·学习·游戏引擎
爱写代码的山山1 天前
虚幻蓝图解决抗锯齿方案
游戏·ue5·游戏引擎·虚幻·抗锯齿化