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()
    {
        
    }
}

运行结果

相关推荐
天天进步20159 分钟前
依赖注入的艺术:Composer 与模块化设计—— QuantConnect/Lean 源码分析系列一
c#
用户44884667106038 分钟前
.NET进阶——深入理解线程(1)同步异步与单线程多线程的区分
c#·.net
编程乐趣1 小时前
qdrant-dotnet:官方提供的开源 .NET 客户端库,用于与 Qdrant 向量搜索引擎操作!
c#·.net
SmoothSailingT1 小时前
C#——单例模式
开发语言·单例模式·c#
Lv11770081 小时前
Visual Studio 中的字符串
ide·笔记·c#·visual studio
Lv11770081 小时前
Visual Studio中的 var 和 dynamic
ide·笔记·c#·visual studio
wuguan_1 小时前
C#之List数组
开发语言·c#·list
工程师0072 小时前
C# 反射与泛型深度结合详解
c#·反射·泛型
feifeigo1232 小时前
C#中实现控件拖动功能
开发语言·c#
曹牧2 小时前
C#:List<string>类型的集合转换成用逗号分隔的字符串
开发语言·c#·list