您的位置:首页 > 移动开发 > Unity3D

lua 在unity 中的协程使用

2014-04-14 15:43 666 查看
最近尝试在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函数

    void Update()

    {

        if(Time.frameCount%5== 0)

        {

            //Debug.Log(Time.realtimeSinceStartup+", "+Time.deltaTime);

            CallMethond("CheckCoroutine");

        }

        //CallMethond("Update");

    }

在lua中实际使用:

lua中例子函数定义:

co2 = coroutine.create(
function ()
    local a= 0;
    while true 
    do
        if a>3 then
            break
        end
    
        a=a+1;
        Print("co2:  "..a.." "..Time.realtimeSinceStartup);
        WaitSeconds(co2, 1);
    end
    
    WaitSeconds(co2, 1);
    Print("after wait:  "..a.." "..Time.realtimeSinceStartup);
    for i=1, 3 do
        WaitSeconds(co2, 1);
        Print("for:  "..a.." "..Time.realtimeSinceStartup);
    end
end
)

lua中函数调用:

      在需要调用的地方启动第一次函数,例如在Start函数调用:

function Start()
     coroutine.resume(co2);
end

    之后co2就会像在c#里面一样自动执行下去了。  

  

这样就可以像c#一样在lua中使用协程了:)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua unity 协程 coroutine