lua 在unity 中的协程使用

本文介绍了如何在Unity中利用Lua的coroutine实现协程功能。通过在C#的Update方法中定时调用Lua的CheckCoroutine函数,配合lua中的coroutine.create和coroutine.resume,实现了与Unity协程类似的效果。示例代码展示了从启动到执行一系列延时操作的过程。
摘要由CSDN通过智能技术生成

最近尝试在unity中用上lua。

而其中会遇到的一个问题就是unity中普遍使用的协程在lua中如何实现。

最终经过考虑之后决定用lua的coroutine来实现。最终的使用与unity的协程类似。

下面是实现代码:


--[[
  use to stop the coroutine for a while.
  should be call once a while to check if need to resume the coroutine.
]]--

coroutine_table= {}

function CheckCoroutine()
  for k,v in pairs(coroutine_table)  do
    if v[1] ~= nil and v[2] ~= nil then
      if (Time.realtimeSinceStartup-v[1])> v[2] then
        --v[1]= Time.realtimeSinceStartup;
        local ret= coroutine.resume(k);
        if not ret then
          --set table value to nil. then the key will be delete.
          coroutine_table[k]= nil;
          
          Print("[remove coroutine.]");
        end
      end  
   	end  
  end
end

function WaitSeconds(corout, time)
  if coroutine_table[corout] ~= nil then
    coroutine_table[corout][1]= Time.realtimeSinceStartup;
    coroutine_table[corout][2]= time;
    --Print("[exist---] "..coroutine_table[corout][1].."  "..coroutine_table[corout][2]);
  else
    -- coroutine_value   [1]: last update time    [2]:interval
    local coroutine_value= {Time.realtimeSinceStartup, time};
    coroutine_table[corout]= coroutine_value;
    --Print("[not exist---] "..coroutine_table[corout][1].."  "..coroutine_table[corout][2]);
    Print("[add coroutine.]");
  end
  
  --pause the function
  coroutine.yield();
end

因为我没找到可以在lua中定时执行任务的方法,所以我在unity中定时会去调用lua的check方法

在unity c#中调用方式:

  在update中调用lua的CheckCoroutine函数

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值