APSchmidt 发表于 2023-4-9 11:39

Unity Xlua 之 Lua调用C#(四)

Unity Xlua 之 Lua调用C#(四)

一.Lua和系统类,系统委托调用

系统自定义的类或者委托,当我们需要调用时要加时,不能直接加入
publicstaticclassLesson10{privatestatic List<Type> allCSharpCallLuaList =newList<Type>(){typeof(UnityAction<float>)};privatestatic List<Type> allLuaCallCSharpList =newList<Type>(){typeof(GameObject),typeof(Rigidbody),};}GameObject = CS.UnityEngine.GameObject

local sliderObj = GameObject.Find("Slider")local sliderComponent = sliderObj:GetComponent(typeof(CS.UnityEngine.UI.Slider))
sliderComponent.onValueChanged:AddListener(function(f)print(f)end)二.Lua调用携程

测试后发现需要在unity中添加标签,携程才能正常调用


util =require("xlua.util")


GameObject = CS.UnityEngine.GameObject
WaitForSeconds = CS.UnityEngine.WaitForSeconds


local go =GameObject("Coroutine")local mono = go:AddComponent(typeof(CS.TestMono))

func =function()local a =0whiletruedoprint(a)
      a = a +1
      coroutine.yield(WaitForSeconds(0.5))if a >=10then
            mono:StopCoroutine(b)endendend

b = mono:StartCoroutine(util.cs_generator(func))三.Lua调用泛型方法

Lua本身只支持,有参有类约束的泛型方法,其余泛型方法都不支持除非使用Xlua为其提供的方法,但是不建议使用有局限性如果打包为Mono方式的话可以,但是打包为il2cpp方式有局限性(具体参考下图)
publicclassLesson12{publicclassTestFather{}publicclassTestChild:TestFather, ITest
    {}publicinterfaceITest{}publicvoidTestFun1<T>(T t1,T t2)where T : TestFather
    {
      Debug.Log("有参有约束");}publicvoidTestFun2<T>(T t1){
      Debug.Log("有参无约束");}publicvoidTestFun3<T>()where T : TestFather
    {
      Debug.Log("无参有约束");}publicvoidTestFun4<T>(T t1)where T : ITest
    {
      Debug.Log("有参有接口约束");}}Lesson12 = CS.Lesson12
TestFather = Lesson12.TestFather
TestChild = Lesson12.TestChild

local l12 =Lesson12()local testFather =TestFather()local testChild =TestChild()

l12:TestFun1(testFather,testChild)
l12:TestFun1(testChild,testFather)--l12:TestFun2(testFather)--l12:TestFun2(testChild)local testFun2 = xlua.get_generic_method(CS.Lesson12,"TestFun2")local testFun2_R =testFun2(CS.System.Int32)testFun2_R(l12,123)local testFun3 = xlua.get_generic_method(CS.Lesson12,"TestFun3")local testFun3_R =testFun3(TestFather)testFun3_R(l12)local testFun4 = xlua.get_generic_method(CS.Lesson12,"TestFun4")local testFun4_R =testFun4(TestChild)testFun4_R(l12,testChild)print("*********Lua调用C# 泛型函数相关知识点***********")local obj = CS.Lesson12()local child = CS.Lesson12.TestChild()local father = CS.Lesson12.TestFather()--支持有约束有参数的泛型函数
obj:TestFun1(child, father)
obj:TestFun1(father, child)--lua中不支持 没有约束的泛型函数--obj:TestFun2(child)--lua中不支持 有约束 但是没有参数的泛型函数--obj:TestFun3()--lua中不支持 非class的约束--obj:TestFun4(child)--有一定的使用限制--Mono打包 这种方式支持使用--il2cpp打包如果泛型参数是引用类型才可以使用--il2cpp打包如果泛型参数是值类型,除非C#那边已经调用过了 同类型的泛型参数 lua中才能够被使用--补充知识 让上面 不支持使用的泛型函数 变得能用--得到通用函数--设置泛型类型再使用--xlua.get_generic_method(类, "函数名")local testFun2 = xlua.get_generic_method(CS.Lesson12,"TestFun2")local testFun2_R =testFun2(CS.System.Int32)--调用--成员方法第一个参数 传调用函数的对象--静态方法 不用传testFun2_R(obj,1)
页: [1]
查看完整版本: Unity Xlua 之 Lua调用C#(四)