Lua调用C#类

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

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

print("OK")
--也会执行重定向
--require("Test")
require("L1_CallClass")

L1_CallClass.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))

自定义类

//自定义类
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()
    {
        
    }
}

运行结果

猜你喜欢

转载自blog.csdn.net/holens01/article/details/133823200
今日推荐