xLua的Lua调用C#的2,3,4

news2025/4/15 10:22:07

使用Lua在Unity中创建游戏对象,组件:

相关代码如下:

Lua

--Lua实例化类
--C# Npc obj=new Npc()
--通过调用构造函数创建对象
local obj=CS.Npc()
obj.HP=100
print(obj.HP)
local obj1=CS.Npc("admin")
print(obj1.Name)

--表方法希望调用表成员变量(表:函数())
--为什么是冒号,对象引用成员变量时,会隐性调用this,等同于Lua中的self
print(obj1:Output())

--Lua实例化GameObject
--C#GameObject obj=new GameObject("LuaCreateGO")
CS.UnityEngine.GameObject("LuaCreateGO")
local go =CS.UnityEngine.GameObject("LuaCreateGO")
go:AddComponent(typeof(CS.UnityEngine.BoxCollider))

 C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Npc
{
    public string Name;
    public int HP
    {
        get;
        set;
    }
    public Npc()
    {

    }
    public Npc(string name)
    {
        Name= name;
    }
    public string Output()
    {
        return this.Name;
    }
}
public class LuaCallObject : MonoBehaviour
{
    void Start()
    {
        //GameObject obj = new GameObject("LuaCreate");
        xLuaEnv.Instance.DoString("require('C2L/LuaCallObject')");
    }
    private void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}

运行时如下所示:

 Lua语言测试结构体:

//C#代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public struct TestStruct
{
    public string Name;
    public string Output()
    {
        return Name;
    }
}

public class LuaCallStruct : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallStruct')");
    }
    void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}

 Lua相关代码:

--和对象调用保持一致
local obj=CS.TestStruct()
obj.Name="adminStruct"
print(obj.Name)
print(obj:Output())

  Lua语言测试枚举:

//C#相关代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum TestEnum
{
    LOL=0,
    Dota2
}
public class LuaCallEnum : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallEnum')");
    }
    private void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua相关代码
--C# TestEnum.LOL
--CS.命名空间.枚举名.枚举值
--枚举获得是userdata自定义数据类型,
获得其他语言数据类型时,就是userdata
print(CS.TestEnum.LOL)
print(CS.TestEnum.Dota2)

--转换获得枚举值
print(CS.TestEnum.__CastFrom(0))
print(CS.TestEnum.__CastFrom("Dota2"))

在Lua语言中实现重载:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestOverLoad
{
    public static void Test(int id)
    {
        Debug.Log("数字类型:" + id);
    }
    public static void Test(string name)
    {
        Debug.Log("字符串类类型:" + name);
    }
    public static void Test(int id,string name)
    {
        Debug.Log("两个数值:" + id + "," + name);
    }
}
public class LuaCallOverLoad : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallOverLoad')");
    }
    private void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua语言代码
--数字重载函数
CS.TestOverLoad.Test(99)

--字符串重载函数
CS.TestOverLoad.Test("admin")

--不同参数的重载函数
CS.TestOverLoad.Test(100,"root")

 在Lua语言中实现继承(相关代码如下所示):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Father
{
    public string Name = "father";
    public void Talk()
    {
        Debug.Log("这是父类中的方法");
    }
    public virtual void Overide()
    {
        Debug.Log("这是父类中的虚方法");
    }
}
public class Child : Father
{
    public override void Overide()
    {
        Debug.Log("这是子类中的重写方法"); 
    }
}
public class LuaCallBase : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallBase')");
    }
    private void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--调用Father
local father=CS.Father()
print(father.Name)

father:Overide()

--调用Child
local child=CS.Child()
print(child.Name)
child:Talk()
child:Overide()

 运行如下所示:

Lua语言实现类扩展:

//C#代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;


public class TestExtend
{
    public void Output()
    {
        Debug.Log("类本身带的方法");
    }
}
//类扩展,需要给扩展方法编写的静态类添加[LuaCallCSharp],
//否则Lua无法调用到
[LuaCallCSharp]
public static class MyExtend
{
    public static void Show(this TestExtend obj)
    {
        Debug.Log("类扩展实现的方法");
    }
}
public class LuaCallExtend : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallExtend')");
    }

    // Update is called once per frame
    void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua相关代码
--获取对象
local obj=CS.TestExtend()
obj:Output()
obj:Show()

 运行效果:

Lua语言实现委托:

相关代码如下:

//C#相关代码如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;


public delegate void DelegateLua();
public class TestDelegate
{
    public static DelegateLua Static;
    public DelegateLua Dynamic;
    public static void StaticFunc()
    {
        Debug.Log("C#静态成员函数");
    }
}
public class LuaCallDelegate : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallDelegate')");
    }

    // Update is called once per frame
    void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua相关代码如下
--C#给委托赋值
--TestDelegate.Static=TestDelegate.StaticFunc
--TestDelegate.Static+=TestDelegate.StaticFunc
--TestDelegate.Static-=TestDelegate.StaticFunc
--TestDelegate.Static()

CS.TestDelegate.Static=CS.TestDelegate.StaticFunc
CS.TestDelegate.Static()
--Lua中如果添加了函数到静态委托变量中后,在委托不在使用后,
--记得释放添加的委托函数
CS.TestDelegate.Static=nil
------------------------------------------------------
local func=function()
    print("这是Lua的函数")
end
--覆盖添加委托
--CS.TestDelegate.Static=func
--加减操作前一定要确定已经添加过回调函数
--CS.TestDelegate.Static=CS.TestDelegate.Static+func
--CS.TestDelegate.Static=CS.TestDelegate.Static-func
--调用以前应确定委托有值
--CS.TestDelegate.Static()

--CS.TestDelegate.Static=nil
-------------------------------------------------------
--调用前判定
if(CS.TestDelegate.Static~=nil)
then
	CS.TestDelegate.Static()
end

--根据委托判定赋值方法
if(CS.TestDelegate.Static==nil)
then
	CS.TestDelegate.Static=func
else
	CS.TestDelegate.Static=CS.TestDelegate.Static+func
end
-------------------------------------------------------
local obj=CS.TestDelegate()
obj.Dynamic=func
obj.Dynamic()

obj.Dynamic=nil

运行效果如下所示: 

 Lua语言实现事件:

相关代码如下所示:

//C#相关代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;


public delegate void EventLua();
public class TestEvent
{
    public static event EventLua Static;
    public static void StaticFunc()
    {
        Debug.Log("这是静态函数");
    }
    public static void CallStatic()
    {
        if (Static!= null){
            Static();
        }
    }
    public event EventLua Dynamic;
    public void CallDynamic()
    {
        if (Dynamic != null)
        {
            Dynamic();
        }
    }
}
public class LuaCallEvent : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallEvent')");
    }

    // Update is called once per frame
    void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua相关代码
--C#添加事件 TestEvent.Static+=TestEvent.StaticFunc
--Lua添加事件
CS.TestEvent.Static("+",CS.TestEvent.StaticFunc)
CS.TestEvent.CallStatic()
CS.TestEvent.Static("-",CS.TestEvent.StaticFunc)

--添加动态成员变量
local func=function()
	print("来自于Lua的回调函数")
end

local obj = CS.TestEvent()
obj:Dynamic("+",func)
obj:CallDynamic()
obj:Dynamic("-",func)

 运行效果如图:

 Lua语言测试泛型:

//C#相关代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class TestGenericType
{
    public void Output<T>(T data)
    {
        Debug.Log("泛型方法:"+data.ToString());
    }
    public void Output(float data)
    {
        Output<float>(data);
    }
    public void Output(string data)
    {
        Output<string>(data);
    }
}
public class LuaCallGenericType : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallGenericType')");
    }

    // Update is called once per frame
    void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua相关代码
local obj=CS.TestGenericType()
obj:Output(99)
obj:Output("admin")

运行效果如下:

 Lua语言测试out,ref关键字

//C#相关代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestOutRef
{
    public static string Func1()
    {
        return "Func1";
    }
    public static string Func2(string str1,out string str2)
    {
        str2 = "Func2 out";
        return "Func2";
    }
    public static string Func3(string str1, ref string str2)
    {
        str2 = "Func3 Ref";
        return "Func3";
    }
    public static string Func4(ref string str1, string str2)
    {
        str1 = "Func4 Ref";
        return "Func4";
    }
}
public class LuaCallOutRef : MonoBehaviour
{
    void Start()
    {
        xLuaEnv.Instance.DoString("require('C2L/LuaCallOutRef')");
    }

    // Update is called once per frame
    void OnDestroy()
    {
        xLuaEnv.Instance.Free();
    }
}
--Lua相关代码
local r1=CS.TestOutRef.Func1()
print(r1)


--C# out返回的变量,会赋值给Lua的第二个接受返回值变量
local out2
local r2,out1=CS.TestOutRef.Func2("admin",out2)
print(r2,out1,out2)

--C# ref返回的变量,会赋值给Lua的第二个接受返回值变量
local ref2
local r3,ref1=CS.TestOutRef.Func3("root",ref2)
print(r3,ref1,ref2)

--即使out ref作为第一个参数,其结果依然会以Lua的多个返回值进行返回
local ref4
local r4,ref3=CS.TestOutRef.Func4(ref4,"test")
print(r4,ref3,ref4)

运行测试结果如下所示:

该系列专栏为网课课程笔记,仅用于学习参考。

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

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

相关文章

Debian系统_主板作为路由器_测试局域网设备间网速

Debian系统_主板作为路由器_测试局域网设备间网速 一、360软件测网速 360测出来的网速实际上是宽带的速度&#xff0c;并不是路由器LAN口到电脑这一段的网速 二、使用iperf3 进行双向带宽测试 1、开发板端下载软件 //Debian系统或者/Ubuntu sudo apt update && sudo…

从 macos 切换到 windows 上安装的工具类软件

起因 用了很多年的macos, 已经习惯了macos上的操作, 期望能在windows上获得类似的体验, 于是花了一些时间来找windows上相对应的软件. 截图软件 snipaste​​​​​​ windows和macos都有的软件, 截图非常好用 文件同步软件 oneDrive: 尝试了不同的同步软件, 还是微软在各…

JavaScript中通过array.map()实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等,array.map()的使用详解(附实际应用代码)

目录 JavaScript中通过array.map(&#xff09;实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等&#xff0c;array.map&#xff08;&#xff09;的使用详解&#xff08;附实际应用代码&#xff09; 一、什么时候该使用Array.map()&#xff0…

SQL优化技术分享:从 321 秒到 0.2 秒的性能飞跃 —— 基于 PawSQL 的 TPCH 查询优化实战

在数据库性能优化领域&#xff0c;TPC-H 测试集是一个经典的基准测试工具&#xff0c;常用于评估数据库系统的查询性能。本文将基于 TPCH 测试集中的第 20个查询&#xff0c;结合 PawSQL 自动化优化工具&#xff0c;详细分析如何通过 SQL 重写和索引设计&#xff0c;将查询性能…

密码学基础——DES算法

前面的密码学基础——密码学文章中介绍了密码学相关的概念&#xff0c;其中简要地对称密码体制(也叫单钥密码体制、秘密密钥体制&#xff09;进行了解释&#xff0c;我们可以知道单钥体制的加密密钥和解密密钥相同&#xff0c;单钥密码分为流密码和分组密码。 流密码&#xff0…

在 Linux 终端中轻松设置 Chromium 的 User-Agent:模拟手机模式与自定义浏览体验

在 Linux 系统中&#xff0c;通过终端灵活控制 Chromium 的行为可以大幅提升工作效率。本文将详细介绍如何通过命令行参数和环境变量自定义 Chromium 的 User-Agent&#xff0c;并结合手机模式模拟&#xff0c;实现更灵活的浏览体验。 为什么需要自定义 User-Agent&#xff1f;…

http页面的加载过程

HTTP/2 核心概念 1.1 流&#xff08;Stream&#xff09; • 定义&#xff1a;HTTP/2 连接中的逻辑通道&#xff0c;用于传输数据&#xff0c;每个流有唯一标识符&#xff08;Stream ID&#xff09;。 • 特点&#xff1a; ◦ 支持多路复用&#xff08;多个流并行传输&#…

MySQL【8.0.41版】安装详细教程--无需手动配置环境

一、MySQL 介绍 1. 概述 MySQL 是一个开源的关系型数据库管理系统&#xff0c;由瑞典公司 MySQL AB 开发&#xff0c;现属于 Oracle 旗下。它基于 SQL&#xff08;结构化查询语言&#xff09;进行数据管理&#xff0c;支持多用户、多线程操作&#xff0c;广泛应用于 Web 应用、…

鸿蒙ArkTS实战:从零打造智能表达式计算器(附状态管理+路由传参核心实现)

还在为组件状态混乱、页面跳转丢参数而头疼&#xff1f; 这篇博客将揭秘如何用鸿蒙ArkTS打造一个漂亮美观的智能计算器&#xff1a; ✅ 输入完整表达式&#xff0c;秒出结果——字符串切割简单计算 ✅ 状态管理黑科技——Provide/Consume 实现跨组件实时响应 ✅ 路由传参实战—…

qq邮箱群发程序

1.界面设计 1.1 环境配置 在外部工具位置进行配置 1.2 UI界面设计 1.2.1 进入QT的UI设计界面 在pycharm中按顺序点击&#xff0c;进入UI编辑界面&#xff1a; 点击第三步后进入QT的UI设计界面&#xff0c;通过点击按钮进行界面设计&#xff0c;设计后进行保存到当前Pycharm…

K8S学习之基础七十九:关闭istio功能

关闭istio功能 kubectl get ns --show-labels kubectl label ns default istio-injection-有istio-injectionenabled的命名空间&#xff0c;pod都会开启istio功能 反之&#xff0c;如果要开启istio&#xff0c;在对应命名空间打上该标签即可

上门预约洗鞋店小程序都具备哪些功能?

现在大家对洗鞋子的清洗条件越来越高&#xff0c;在家里不想去&#xff0c;那就要拿去洗鞋店去洗。如果有的客户没时间去洗鞋店&#xff0c;这个时候&#xff0c;有个洗鞋店小程序就可以进行上门取件&#xff0c;帮助没时间的客户去取需要清洗的鞋子&#xff0c;这样岂不是既帮…

蓝桥杯——走迷宫(Java-BFS)

这是一个经典的BFS算法 1. BFS算法保证最短路径 核心机制&#xff1a;广度优先搜索按层遍历所有可能的路径&#xff0c;首次到达终点的路径长度即为最短步数。这是BFS的核心优势。队列的作用&#xff1a;通过队列按先进先出的顺序处理节点&#xff0c;确保每一步探索的都是当…

下载firefox.tar.xz后如何将其加入到Gnome启动器

起因&#xff1a;近期&#xff08;2025-04-07&#xff09;发现firefox公布了130.0 版本&#xff0c;可以对pdf文档进行签名了&#xff0c;想试一下&#xff0c;所以卸载了我的Debian12上的firefox-esr,直接下载了新版本的tar.xz 包。 经过一番摸索&#xff0c;实现了将其加入Gn…

加密≠安全:文件夹密码遗忘背后的数据丢失风险与应对

在数字化时代&#xff0c;保护个人隐私和数据安全变得尤为重要。许多人选择对重要文件夹进行加密&#xff0c;以防止未经授权的访问。然而&#xff0c;一个常见且令人头疼的问题也随之而来——文件夹加密密码遗忘。当你突然发现自己无法访问那些加密的文件夹时&#xff0c;那种…

【开源宝藏】30天学会CSS - DAY12 第十二课 从左向右填充的文字标题动画

用伪元素搞定文字填充动效&#xff1a;一行 JS 不写&#xff0c;效果炸裂 你是否曾经在设计页面标题时&#xff0c;觉得纯文字太寡淡&#xff1f;或者想做一个有动感的文字特效&#xff0c;但又不想引入 JS 甚至 SVG&#xff1f; 在这篇文章中&#xff0c;我们将通过 一段不到…

nginx或tengine服务器,配置HTTPS下使用WebSocket的线上环境实践!

问题描述&#xff1a; HTTPS 下发起WS连接&#xff0c;连接失败&#xff0c;Chrom 浏览器报错。 socket.js:19 Mixed Content: The page at https://app.XXX.com was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint ws://172.16.10.80:903…

【Oracle篇】跨字符集迁移:基于数据泵的ZHS16GBK转AL32UTF8全流程迁移

&#x1f4ab;《博主主页》&#xff1a;奈斯DB-CSDN博客 &#x1f525;《擅长领域》&#xff1a;擅长阿里云AnalyticDB for MySQL(分布式数据仓库)、Oracle、MySQL、Linux、prometheus监控&#xff1b;并对SQLserver、NoSQL(MongoDB)有了解 &#x1f496;如果觉得文章对你有所帮…

西门子S7-1200PLC 工艺指令PID_Temp进行控温

1.硬件需求&#xff1a; 西门子PLC&#xff1a;CPU 1215C DC/DC/DC PLC模块&#xff1a;SM 1231 TC模块 个人电脑&#xff1a;已安装TIA Portal V17软件 加热套&#xff1a;带加热电源线以及K型热电偶插头 固态继电器&#xff1a;恩爵 RT-SSK4A2032-08S-F 其他&#xff1…

vant4+vue3上传一个pdf文件并实现pdf的预览。使用插件pdf.js

注意下载的插件的版本"pdfjs-dist": "^2.2.228", npm i pdfjs-dist2.2.228 然后封装一个pdf的遮罩。因为pdf文件有多页&#xff0c;所以我用了swiper轮播的形式展示。因为用到移动端&#xff0c;手动滑动页面这样比点下一页下一页的方便多了。 直接贴代码…