Lua脚本
print("*****************Lua调用C#类相关知识点******************");
--Lua中使用C#的类非常简单
--固定套路
--CS.命名空间.类名
--Unity类 比如:GameObject Transform等等----CS.UnityEngine.类名
--CS.UnityEngine.GameObject
--通过C#中的类,实现一个对象
--Lua中没有new 所有直接调用通过类名括号就是实例化对象
--默认调用 相当于无参构造
local obj1 = CS.UnityEngine.GameObject();
local obj2 = CS.UnityEngine.GameObject("LuaCall_C#_Class");
--为了方便使用 并且节约性能,定义全局存储C#中的类
--相当于取了一个别名
GameObject=CS.UnityEngine.GameObject;
local obj3 = GameObject("LuaCall_C#_Class_封装测试");
--类中的静态对象 可以直接使用.来调用
local obj4 = GameObject.Find("LuaCall_C#_Class_封装测试");
--得到对象中的成员变量 直接对象.即可
Vector3=CS.UnityEngine.Vector3;
Debug=CS.UnityEngine.Debug;
obj4.transform.position=Vector3(10,10,10);
print(obj4.transform.position);
Debug.Log(obj4.transform.position);
--如果使用对象中成员方法一定要使用:
obj4.transform:Translate(Vector3.right);
Debug.Log(obj4.transform.position);
--使用自己定义的类
local myClassT1 = CS.Test1();
local myClassT2 = CS.LuaCallMyClass.Test2();
myClassT1:Speak("测试说话");
myClassT2:Speak("测试说话2");
--继承了Mono的类,不能直接使用new
local obj5 =GameObject("Lua给物体添加脚本");
obj5:AddComponent(typeof(CS.LuaAddCSharpTest))
C#脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Lua不能直接访问C#,一定是先从C#调用Lua脚本
/// </summary>
public class Main : MonoBehaviour
{
private void Start()
{
LuaMgr.GetInstance().Init();
LuaMgr.GetInstance().DoLuaFile("Main");
// Vector3
//this.gameObject.AddComponent
}
}
public class Test1
{
public void Speak(string str)
{
Debug.Log("无命名空间:Lua调用----"+str);
}
}
namespace LuaCallMyClass
{
public class Test2
{
public void Speak(string str)
{
Debug.Log("有命名空间:Lua调用----" + str);
}
}
}