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

运行结果

相关推荐
我是苏苏3 小时前
C#基础:Winform桌面开发中窗体之间的数据传递
开发语言·c#
水果里面有苹果10 小时前
20-C#构造函数--虚方法
java·前端·c#
[纳川]13 小时前
把word中表格转成excle文件
开发语言·c#·word
lph197214 小时前
快速分页wpf
c#
试行15 小时前
C#System.Runtime.InteropServices.ExternalException (0x80004005): GDI+ 中发生一般性错误。
c#
每日出拳老爷子19 小时前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
程序猿多布1 天前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
阿蒙Amon1 天前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#
开开心心_Every1 天前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text