使用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
    }
}
相关推荐
小清兔5 小时前
c#基础知识
开发语言·数据库·学习·unity·c#·游戏引擎·.net
霜绛5 小时前
Unity笔记(七)——四元数、延迟函数、协同程序
笔记·学习·unity·游戏引擎
★YUI★9 小时前
学习游戏制作记录(保存装备物品技能树和删除存档文件)8.26
学习·游戏·unity·c#
淡海水11 小时前
【URP】[平面阴影]原理与实现
平面·unity·urp·阴影
SmalBox14 小时前
【渲染流水线】[输出阶段]-[双缓冲机制]以UnityURP为例
unity·渲染
黑客影儿15 小时前
在Godot中为您的游戏添加并控制游戏角色的完整技术指南
开发语言·游戏·游戏引擎·godot·gdscript·游戏开发·3d游戏
SimpleUmbrella15 小时前
windows下配置lua环境
c++·lua
weixin_4242946719 小时前
Unity:游戏性能优化!之把分散在各个游戏角色GameObject上的脚本修改为在一个脚本中运行。这样做会让游戏运行更高效?
游戏·unity·性能优化
YF云飞1 天前
车机两分屏运行Unity制作的效果
unity·游戏引擎·个人开发·车机
枯萎穿心攻击1 天前
Unity VS UE 性能工具与内存管理
开发语言·游戏·unity·ue5·游戏引擎·虚幻·虚幻引擎