Lua调用C#类

先创建一个Main脚本作为主入口,挂载到摄像机上

cs 复制代码
public class Main : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        LuaMgr.GetInstance().Init();
        LuaMgr.GetInstance().DoLuaFile("Main");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

编写Lua脚本

Main.lua

Lua 复制代码
print("OK")
--也会执行重定向
--require("Test")
require("L1_CallClass")

L1_CallClass.lua

Lua 复制代码
--Lua中使用C#类
--CS.命名空间.类名
--Unity的类(GameObject Transform等
--在CS.UnityEngine

--默认调用无参构造
local obj1 = CS.UnityEngine.GameObject()
local obj2 = CS.UnityEngine.GameObject("命名")

--节约性能
GameObject = CS.UnityEngine.GameObject
local obj3 = GameObject("节约性能")

--静态方法直接.使用
local obj4 = GameObject.Find("命名")
print(obj4.transform.position)

--使用成员方法,一定要加:
Vector3 = CS.UnityEngine.Vector3
obj4.transform:Translate(Vector3.right)
print(obj4.transform.position)

--自定义类
local t = CS.Test1()
t:Speak("说话")
local t2 = CS.Holens.Test2()
t2:Speak("说话")

--继承Mono的类 不能直接New
local obj5 = GameObject("加脚本测试")
--xLua提供了一个重要方法 typeof方法
obj5:AddComponent(typeof(CS.LuaCallC))

自定义类

cs 复制代码
//自定义类
public class Test1
{
    public void Speak(string str)
    {
        Debug.Log("Test1"+str);
    }
}

namespace Holens
{
    public class Test2
    {
        public void Speak(string str)
        {
            Debug.Log("Test2" + str);
        }
    }
}
public class LuaCallC : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

运行结果

相关推荐
hez201010 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务2 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间3 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec3 天前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#