使用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
    }
}
相关推荐
七夜zippoe1 小时前
OpenClaw 内置工具详解
unity·ai·游戏引擎·openclaw·内置工具
mxwin6 小时前
Unity Shader 细节贴图技术在不增加显存开销的前提下,有效提升近距离纹理细节的渲染质量
unity·游戏引擎·贴图
魔士于安7 小时前
unity 低多边形 动物 带场景 有氛围感
游戏·unity·游戏引擎·贴图
小贺儿开发8 小时前
Unity3D 摩斯与中文电码转换工具
科技·unity·人机交互·工具·实践·实用·科普应用
魔士于安9 小时前
unity 动物包 大象 鹿 狐狸
游戏·unity·游戏引擎·贴图·模型
mxwin12 小时前
Unity URP 中 Mipmap 纹理多级渐远技术 解决远处纹理闪烁(摩尔纹)与性能优化的完整指南
unity·游戏引擎
mxwin12 小时前
Unity Shader Blinn-Phong vs PBR传统经验模型与现代物理基础渲染
unity·游戏引擎·shader
风酥糖14 小时前
Godot游戏练习01-第23节-新增Player名称显示
游戏·游戏引擎·godot
mxwin14 小时前
Unity Shader BRDF双向反射分布函数
unity·游戏引擎
十五年专注C++开发14 小时前
Cocos2d - x: 一款开源跨平台 2D 游戏框架
运维·c++·游戏·开源·游戏引擎·cocos2d