使用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
    }
}
相关推荐
nnsix1 小时前
Unity Addressables 笔记
unity·游戏引擎
RReality1 小时前
【Unity Shader URP】视差贴图 实战教程
ui·平面·unity·游戏引擎·图形渲染·贴图
weixin_4080996710 小时前
触动精灵调用身份证OCR识别API实现智能信息录入(Lua脚本实战)
junit·ocr·lua·自动化脚本·石榴智能·身份证ocr识别·触动精灵
小清兔16 小时前
Addressable的设置打包流程
笔记·游戏·unity·c#
3D霸霸18 小时前
Sourcetree 拉取新工程
数据仓库·unity
程序员正茂19 小时前
Unity3d中RawImage显示视频画面偏白的解决方法
unity·视频·rawimage
mxwin21 小时前
Unity SetPassCall和DrawCall的区别是什么
unity·游戏引擎·shader
电子云与长程纠缠1 天前
UE5 GameFeature创建与使用
开发语言·学习·ue5·游戏引擎
moonsims1 天前
AiBrainLink:无人化系统异构连接架构-多执行体、多链路(5G+自组网)、多业务流(控制、遥测、视频、文件)透明传输、多对多控制
unity·游戏引擎
小贺儿开发1 天前
Unity3D 年会抽奖工具(附体验链接)
数据库·unity·excel·人机交互·工具·抽奖·互动