Unity XLua之协程

如何使用xlua实现协程,示例代码如下:

转载请注明出处:https://www.cnblogs.com/jietian331/p/10735773.html

 1 local unpack = unpack or table.unpack;
 2 local function async_to_sync(async_func, callback_pos)
 3     return function(...)
 4         local _co = coroutine.running() or error ('this function must be run in coroutine')
 5         local rets
 6         local waiting = false
 7         local function cb_func(...)
 8             if waiting then
 9                 assert(coroutine.resume(_co, ...))
10             else
11                 rets = {...}
12             end
13         end
14         local params = {...}
15         table.insert(params, callback_pos or (#params + 1), cb_func)
16         async_func(unpack(params))
17         if rets == nil then
18             waiting = true
19             rets = {coroutine.yield()}
20         end
21         
22         return unpack(rets)
23     end
24 end
25 
26 -- 异步协程
27 local gameobject = CS.UnityEngine.GameObject('XLua_Coroutine_Runner');
28 CS.UnityEngine.Object.DontDestroyOnLoad(gameobject);
29 local csCoroutineRunner = gameobject:AddComponent(typeof(CS.XLuaCoroutineRunner));
30 local function AsyncYieldReturn(toYield, cb)
31     csCoroutineRunner:YieldAndCallback(toYield, cb)
32 end
33 local yieldReturn = async_to_sync(AsyncYieldReturn);
34 
35 -- 协程
36 local co = coroutine.create(function()
37     local url = CS.Common.LoadHelp.GetAssetBundleStreamingUrl("xxx.json");
38     local www = CS.UnityEngine.WWW(url);
39     yieldReturn(www);
40     
41     local text = www.text;
42     print(text);
43 end);
44 
45 coroutine.resume(co);

 

posted @ 2019-04-19 14:33  孤独の巡礼  阅读(1555)  评论(0编辑  收藏  举报