xlua游戏热更新(C#访问lua)

news2024/10/7 14:29:54

xlua作为Unity资源热更新的重要解决方案api,在Tecent重多游戏中被采用,本文通过案例去讲解xlua代码结构层次。

/*
 * Tencent is pleased to support the open source community by making xLua available.
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

using UnityEngine;
using XLua;

namespace XLuaTest
{
    public class Helloworld : MonoBehaviour
    {
        // Use this for initialization
        void Start()
        {
            //创建xlua虚拟机
            LuaEnv luaenv = new LuaEnv();
            luaenv.DoString("print('hello xlua!')");
            luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
            //释放资源
            luaenv.Dispose();
        }

        // Update is called once per frame
    }
}

image.png

加载lua文件

Resources.Load(“xlua/xx.lua”) 加载

创建Resources 目录下xx.lua.txt文件

//创建xlua虚拟机【建议全局唯一】
LuaEnv luaenv = new LuaEnv();
//加载lua脚本资源
TextAsset textAsset = Resources.Load<TextAsset>("xlua/hello.lua");
luaenv.DoString(textAsset.ToString());

loader加载

luaenv.DoString("require 'xlua/hello'"); //require + 'lua文件名称不加扩展名'
//require 实际上是逐个查找loader文件 是否存在指定文件

自定义loader

挨个查找loader,若某个loader返回了字节数组,那么便不继续查找了

  //加载loader
            luaenv.AddLoader(Myloader);
            
            luaenv.DoString("require 'xlua/hello'");
            //挨个查找loader,若某个loader返回了字节数组,那么便不继续查找了
            //释放资源
            luaenv.Dispose();

		/// <summary>
        /// 自定义loader
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private byte[] Myloader(ref string filePath)
        {
            print(filePath);
            string s = "print(123)";
            return Encoding.UTF8.GetBytes(s);
        }

image.png

构建Assets/StreamingAssets文件夹

  private byte[] Myloader(ref string filePath)
        {
            //print(filePath);
            string absPath = Application.streamingAssetsPath + "/" + filePath + ".lua.txt";
            return Encoding.UTF8.GetBytes(File.ReadAllText(absPath));
        }

C#访问lua文件

全局变量

加载文件成功后,访问lua文件中的全局变量
–number 可以对应int float double

           //通过luaenv 访问变量
            int integer_Lua = luaenv.Global.Get<int>("Integer");
            string name_Lua = luaenv.Global.Get<string>("Name");
            
            Debug.Log(integer_Lua + name_Lua);

//lua文件中

person = {
    Name = "James",
    Sno = 23,
    
    eat = function()
        print("i'm eating!")
    end
    
}
//
//C#
class Person
        {
            public string _name;
            public int _sno;
        }
 Person luaPerson = luaenv.Global.Get<Person>("person");
            print(luaPerson._sno + ":" + luaPerson._name);

接口

IPerson luaPerson = luaenv.Global.Get<IPerson>("person");
 print(luaPerson.sno + ":" + luaPerson.name);


[CSharpCallLua]
        interface IPerson
        {
            string name { get; set; }
            int sno { get; set; }
            void eat();
        }

字典

dic = {
    china = 1,
    america = 2,
    uk  = 3,
}
 //通过字典遍历
            Dictionary<string,int> dic =  luaenv.Global.Get<Dictionary<string, int>>("dic");
            foreach (var key in dic.Keys)
            {
                print(key + ":" + dic[key]);
            }

image.png

列表

list = {'sdahjk',12,123,'12'}
  //通过list访问
            List<object> list =  luaenv.Global.Get<List<object>>("list");
            foreach (var target in list)
            {
                print(target.ToString());
            }

再将上述数据通过List读取一次
image.png

LuaTable

LuaTable table = luaenv.Global.Get<LuaTable>("person");
            table.Get<string>("name");

函数

 [CSharpCallLua]
        delegate int Add(int a, int b);

//函数
            Add add = luaenv.Global.Get<Add>("add");
            print(add(3,5));
            add = null;

lua多返回值通过,out 变量接受

add = function(a,b)
    return a + b,a,b
end
 delegate int Add2(int a, int b, out int resa, out int resb);

使用LuaFunction (性能差)

LuaFunction add = luaenv.Global.Get<LuaFunction>("add");
            object[] objects = add.Call(3, 5);
            print(objects[0]);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1191197.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

WPF中数据绑定验证深入讲解

WPF中数据绑定验证深入讲解 WPF在用户输入时&#xff0c;提供了验证功能&#xff0c;通常验证使用以下两种方式来实现&#xff1a; 在数据对象中引发错误。通常是在属性设置过程中抛出异常&#xff0c;或者在数据类中实现INotifyDataErrorInfo或IDataErrorInfo接口。在绑定级…

【docker容器 redis密码没有生效解决办法】

遇到的问题&#xff1a;启动docker版本redis认证失败&#xff0c;导致web端启动失败 报错内容如下 redis.exceptions.ResponseError: AUTH called without any password configured for the default user. Are you sure your configuration is correct? 做的一系列操作&…

野火霸天虎 STM32F407 学习笔记_4 构建库函数尝试;使用固件库点亮 LED 灯

构建库函数 创建一个通用的模板&#xff0c;后面写程序直接使用这个模板。 $ ls Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2023/11/8 23:27 Libraries d----- …

Django文件配置、request对象、连接MySQL、ORM

文章目录 Django静态文件及相关配置静态文件前言静态文件相关配置 form表单request对象request请求结果GET请求POST请求 pycharm连接数据库Django连接MySQLDjango ORM简介 Django静态文件及相关配置 在此篇博客我将以一个用户登录页面来引入相关知识 首先我们先编写一个html页面…

【计算机网络笔记】网络层服务模型——数据报网络

系列文章目录 什么是计算机网络&#xff1f; 什么是网络协议&#xff1f; 计算机网络的结构 数据交换之电路交换 数据交换之报文交换和分组交换 分组交换 vs 电路交换 计算机网络性能&#xff08;1&#xff09;——速率、带宽、延迟 计算机网络性能&#xff08;2&#xff09;…

不可忽视的国外服务器地址IP选择指南

​  在如今互联网高速发展的时代&#xff0c;海外服务器扮演着重要的角色。选择合适的国外服务器IP地址却是一项复杂而又关键的任务。本文将为您介绍一些不可忽视的国外服务器地址IP选择指南。 私有IP地址&#xff1a; 私有IP地址是指在局域网内使用的IP地址&#xff0c;用于…

vue Sts认证后直传图片到阿里云OSS

后端进行sts认证生成临时身份凭证&#xff0c;前端通过凭证直传图片等文件到OSS中 一 OSS配置 增加用户和角色&#xff0c;创建OSS bucket 1.1 添加用户 登录阿里云管理控制台&#xff0c;右侧头像&#xff0c;进入访问控制 点击左侧导航栏的身份管理的用户&#xff0c;点击…

python- time模块

3种时间格式之间的转换 &#xff1a; 1、时间戳->格式化时间 time.localtime(timestamp)&#xff1a;北京时间 time.gmtime(timestamp) &#xff1a;伦敦时间 2、格式化时间->时间戳时间

PHP网站源码 知识付费分站代理自助下单系统 自带多款模板

源码测评&#xff1a;功能很齐全&#xff0c;有可以对接的总站&#xff0c;应该是对接好就可以推广赚钱了&#xff0c;但是这种感觉能赚钱的就那么几个人&#xff0c;见仁见智吧&#xff01; 截图演示&#xff1a; 转载自 https://www.qnziyw.cn/cmsmb/qtcms/3952.html

【JAVA学习笔记】67 - 坦克大战1.5 - 1.6,防止重叠,记录成绩,选择是否开新游戏或上局游戏,播放游戏音乐

项目代码 https://github.com/yinhai1114/Java_Learning_Code/tree/main/IDEA_Chapter20/src 增加功能 1.防止敌人坦克重叠运动 2.记录玩家的成绩&#xff0c;存盘退出 3.记录当时的敌人坦克坐标&#xff0c;存盘退出 4.玩游戏时&#xff0c;可以选择是开新游戏还是继续上局…

说说对React Hooks的理解?解决了什么问题?

一、是什么 Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性 至于为什么引入hook&#xff0c;官方给出的动机是解决长时间使用和维护react过程中常遇到的问题&#xff0c;例如&#xff1a; 难以重用和共享组件中的与状态…

ChatGPT:something went wrong

今天下午不知什么原因&#xff0c;ChatGPT无法使用。我原来在使用ChatGPT for chrome&#xff0c;返回了一个答案&#xff0c;后来在网页端无法使用&#xff0c;以为是这个chrome插件泄露API KEY导致的。注销账号&#xff0c;删除API KEY后&#xff0c;wrong问题仍然存在。 我…

读程序员的制胜技笔记08_死磕优化(上)

1. 过早的优化是万恶之源 1.1. 著名的计算机科学家高德纳(Donald Knuth)的一句名言 1.2. 原话是&#xff1a;“对于约97%的微小优化点&#xff0c;我们应该忽略它们&#xff1a;过早的优化是万恶之源。而对于剩下的关键的3%&#xff0c;我们则不能放弃优化的机会。” 2. 过早…

12 # 手写 findIndex 方法

findIndex 的使用 findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。 <script>var arr [1, 3, 5, 7, 8];var result arr.findIndex(function (ele, index, array) {console.log("ele----->", ele);conso…

【Java】SPI在Java中的实现与应用

一、SPI的概念 1.1、什么是API&#xff1f; API在我们日常开发工作中是比较直观可以看到的&#xff0c;比如在 Spring 项目中&#xff0c;我们通常习惯在写 service 层代码前&#xff0c;添加一个接口层&#xff0c;对于 service 的调用一般也都是基于接口操作&#xff0c;通…

已解决:rm: 无法删除“/opt/module/zookeeper-3.4.10/zkData/zookeeper_server.pid“: 权限不够

解决&#xff1a; ZooKeeper JMX enabled by default Using config: /opt/module/zookeeper-3.4.10/bin/../conf/zoo.cfg Stopping zookeeper ... /opt/module/zookeeper-3.4.10/bin/zkServer.sh: 第 182 行:kill: (4149) - 不允许的操作 rm: 无法删除"/opt/module/zooke…

开发知识点-Python

Python从小白到入土 python渗透测试安全工具开发锦集Python安全工具编程基础第一章 Python在网络安全中的应用第一节 Python黑客领域的现状第二节 我们可以用Python做什么第三节 第一章课程内容总结 第二章 python安全应用编程入门第一节 Python正则表达式第二节 Python Web编程…

C++二分查找算法:阶乘函数后 K 个零

涉及知识点 二分查找 数学 题目 f(x) 是 x! 末尾是 0 的数量。回想一下 x! 1 * 2 * 3 * … * x&#xff0c;且 0! 1 。 例如&#xff0c; f(3) 0 &#xff0c;因为 3! 6 的末尾没有 0 &#xff1b;而 f(11) 2 &#xff0c;因为 11! 39916800 末端有 2 个 0 。 给定 k&a…

Python--列表及其应用场景

1.为什么需要列表 思考&#xff1a;有一个人的姓名(laowang)怎么书写存储程序&#xff1f; 用 变量。如&#xff1a;name laowang 但是&#xff0c;如果要记录很多人的名字&#xff0c;怎么办&#xff1f; 思考&#xff1a; 如果一个班级100位学生&#xff0c;每个人的…

17 Linux 中断

一、Linux 中断简介 1. Linux 中断 API 函数 ① 中断号 每个中断都有一个中断号&#xff0c;通过中断号可以区分出不同的中断。在 Linux 内核中使用一个 int 变量表示中断号。 ② request_irq 函数 在 Linux 中想要使用某个中断是需要申请的&#xff0c;request_irq 函数就是…