最近尝试在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函数