toLua访问C#的类,固定套路 命名空间.类名,比如GameObject,在lua中调用就是UnityEngine.GameObject。
1、通过C#实例化一个对象,因为lua中没有new,所以我们直接使用类名()来实例化对象。
local obj1 = UnityEngine.GameObject()
local obj2 = UnityEngine.GameObject("Master_Xue")
2、在使用中,为了方便实用并且节约性能,我们通常定义全局变量来存储我们C#中的类
GameObject = UnityEngine.GameObject
使用方式如下:
local obj3 = GameObject("Master_Xue3")
3、类中的静态对象都可以通过.来调用,静态对象的成员变量也是直接对象.属性的方式来获取。
local obj4 = GameObject.Find("Master_Xue")
print(obj4.transform.position.x)
4、需要注意的是,部分类例如Debug默认使用会报错,因为我们没有把他们加入到CustomSetting文件中,
在使用时,需要将其加入到CustomSetting中的BindType[] customTypeList中。
_GT(typeof(Debug)),
之后点击lua->Generate all生成文件之后即可正常使用
Debug = UnityEngine.Debug
Debug.Log(obj4.transform.position.x)
5、如果要使用成员方法,一定要用:
Vector3 = UnityEngine.Vector3
obj4.transform:Translate(Vector3.right)
Debug.Log(obj4.transform.position.x)
6、继承了Mono的类不能直接new的,通过Gameobject的Addcomponent方法添加脚本,同样需要将其加入到CustomSetting中的BindType[] customTypeList中。
local obj5 = GameObject("加脚本测试")
obj5:AddComponent(typeof(LuaCallCSharp))
7、没有继承Mono的类,依然需要将其加入到CustomSetting中的BindType[] customTypeList中。
public class Test{
public void Speak(string str){
Debug.Log("Test:"+str);
}
}
namespace Master_Xue{
public class Test2{
public void Speak (string str){
Debug.Log("Test2:"+str);
}
}
}
local t1 = Test()
t1:Speak("t1说话")
local t2 = Master_Xue.Test2()
t2:Speak("t2说话")