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

运行结果

相关推荐
ii_best12 分钟前
按键精灵安卓ios辅助工具脚本:实用的文件插件(lua开源)
android·开发语言·ios·lua
浅陌sss15 分钟前
在VS2022中使用Lua与c交互(二)
c语言·lua
电商api接口开发2 小时前
ASP.NET MVC 入门与提高指南六
c#·asp.net·mvc
宝桥南山3 小时前
Azure Devops - 尝试一下在Pipeline中使用Self-hosted Windows agent
microsoft·微软·c#·.netcore·azure·devops
冰茶_11 小时前
WPF之TextBox控件详解
学习·microsoft·微软·c#·wpf
大飞pkz15 小时前
【Unity】使用XML进行数据读存的简单例子
xml·unity·c#·游戏引擎·游戏开发·数据读写
编程乐趣19 小时前
基于C#开发的适合Windows开源文件管理器
开发语言·windows·c#
code_shenbing21 小时前
C# 实现列式存储数据
开发语言·c#·存储
code_shenbing21 小时前
.NET Core 数据库ORM框架用法简述
数据库·c#·.netcore·orm
ghost1431 天前
C#学习第20天:垃圾回收
开发语言·学习·c#