使用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
    }
}
相关推荐
枯萎穿心攻击3 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
X_StarX11 小时前
【Unity笔记02】订阅事件-自动开门
笔记·学习·unity·游戏引擎·游戏开发·大学生
霸王•吕布15 小时前
游戏引擎中顶点着色&像素着色
游戏引擎·顶点着色器·像素着色器·顶点颜色·顶点uv·顶点法向
Thomas_YXQ18 小时前
Unity URP法线贴图实现教程
开发语言·unity·性能优化·游戏引擎·unity3d·贴图·单一职责原则
徐子竣1 天前
[学习记录]Unity-Shader-几何着色器
unity·游戏引擎·着色器
EQ-雪梨蛋花汤1 天前
【Part 3 Unity VR眼镜端播放器开发与优化】第四节|高分辨率VR全景视频播放性能优化
unity·音视频·vr
与火星的孩子对话1 天前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
幻世界2 天前
【Unity智能模型系列】Unity + MediaPipe + Sentis + ArcFace模型:构建高效人脸识别比对系统
unity·游戏引擎
漫游者Nova2 天前
虚幻引擎Unreal Engine5恐怖游戏设计制作教程,从入门到精通从零开始完整项目开发实战详细讲解中英字幕
ue5·游戏引擎·虚幻·游戏开发完整教程·恐怖游戏开发
死也不注释2 天前
【Unity 编辑器工具开发:GUILayout 与 EditorGUILayout 对比分析】
unity·编辑器·游戏引擎