0
点赞
收藏
分享

微信扫一扫

Unity ToLua 之 Lua调用C#(三)

龙毓七七 2022-03-30 阅读 71

Unity ToLua 之 Lua调用C#(三)

一.ToLua调用C#重载函数

  • Lua对于精度和Ref区分的不是很好
    在这里插入图片描述
local a = Lesson07()
a:Test(99)
a:Test(99.99)
a:Test("999")

a:Test(20,30)
a:Test(20,nil)

二.ToLua调用C#中的委托

  • ToLua中执行委托需要现在C#中添加一个执行委托的方法才能执行
    XLua中可以直接执行
  • ToLua中可以直接+=Event,但是XLua中不可以
    XLua中使用 事件名("+/-",函数)
public class Lesson08
{
    public UnityAction del;
    public event UnityAction eventAction;

    public void OnDel()
    {
        del?.Invoke();
    }

    public void OnEventAction()
    {
        eventAction?.Invoke();
    }

    public void OnClearEventAction()
    {
        eventAction = null;
    }
}
local myFunc = function()
    print("Lua Function")
end

local a = Lesson08()

--第一次添加不能+=
a.del = myFunc
a.del = a.del + myFunc
a.del = a.del - myFunc
--ToLua中执行委托需要现在C#中添加一个执行委托的方法才能执行
--XLua中可以直接执行
a:OnDel()

--ToLua中可以直接+=Event,但是XLua中不可以
--XLua中使用 事件名("+/-",函数)
a.eventAction = a.eventAction + myFunc
a:OnEventAction()
a:OnClearEventAction()

a.eventAction = a.eventAction + function()
    print("匿名方法")
end
a:OnEventAction()

三.ToLua调用C#中的协程

  • 需要添加代码来绑定协程
  • LuaCoroutine.Register(_luaState,this);
  •     //携程相关初始化
      LuaLooper loop = gameObject.AddComponent<LuaLooper>();
      loop.luaState = luaState;
      //lua携程注册
      LuaCoroutine.Register(luaState, this);
      //委托工厂初始化 lua和C#之间相互访问时 要使用对应委托
      DelegateFactory.Init();
      //Lua中使用Unity的类需要进行绑定 如果不绑定 会报错
      LuaBinder.Bind(luaState);
    
local coDelay = nil
function StartDelay()
    --ToLua提供的开启协程的方式
    coDelay = StartCoroutine(Delay)
end

function Delay()
    local a = 0;
    while true do
        print(a)
        WaitForSeconds(1)
        --Yield(0)
        --Yield(异步加载返回值)
        --...
        a = a + 1
        if(a>5) then
            StopCoroutine(coDelay)
            break
        end
    end
end

StartDelay()
举报

相关推荐

Lua调用C#类

Unity GC + C# GC + Lua GC原理

Unity tolua 常用方法

Lua调用C++

C语言调用lua

0 条评论