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


    1、Lua脚本 

    入口脚本

    1. print("OK")
    2. --也会执行重定向
    3. require("Test")

    测试脚本

    1. print("TestScript")
    2. testNum = 1
    3. testBool = true
    4. testFloat = 1.2
    5. testStr = "123"
    6. function testFun()
    7. print("无参无返回")
    8. end
    9. function testFun2(a)
    10. print("有参有返回")
    11. return a
    12. end

    2、C#脚本

    (1)获取全局变量

    1. public class L4 : MonoBehaviour
    2. {
    3. // Start is called before the first frame update
    4. void Start()
    5. {
    6. //自己编写的Lua管理器
    7. //初始化管理器
    8. LuaMgr.GetInstance().Init();
    9. //执行Main脚本(调用了Test脚本)
    10. LuaMgr.GetInstance().DoLuaFile("Main");
    11. //得到全局变量(只是复制到C#,改不了)
    12. int i = LuaMgr.GetInstance().Global.Get<int>("testNum");
    13. print(i);
    14. //修改全局变量
    15. LuaMgr.GetInstance().Global.Set("testNum", 2);
    16. i = LuaMgr.GetInstance().Global.Get<int>("testNum");
    17. print(i);
    18. }
    19. }

    执行结果

    (2)获取全局函数

    1. using XLua;
    2. public class L5 : MonoBehaviour
    3. {
    4. // Start is called before the first frame update
    5. void Start()
    6. {
    7. LuaMgr.GetInstance().Init();
    8. LuaMgr.GetInstance().DoLuaFile("Main");
    9. #region 无参无返回
    10. //第一种方法 通过 GetFunction方法获取(需要引用命名空间)
    11. LuaFunction function = LuaMgr.GetInstance().Global.Get("testFun");
    12. //调用 无参无返回
    13. function.Call();
    14. //执行完过后
    15. function.Dispose();
    16. #endregion
    17. #region 有参有返回
    18. //第一种方式 通过luafunction 的 call来访问
    19. LuaFunction function2 = LuaMgr.GetInstance().Global.Get("testFun2");
    20. Debug.Log("有参有返回值 Call:" + function2.Call(10)[0]);
    21. #endregion
    22. }
    23. }
  • 相关阅读:
    Hive执行计划之只有map阶段SQL性能分析和解读
    只需一行Python代码即可玩20几款小游戏
    05 动态SQL&&标签
    vue-饼形图-详细
    手写Mybatis
    【数据结构】单链表
    【HCIE考试喜报】2022年11月11日考试通过
    算法练习4——删除有序数组中的重复项 II
    最终稿第5部分理论知识考卷模拟
    【算法基础】TOPSIS法
  • 原文地址:https://blog.csdn.net/holens01/article/details/133771005