xLua中也会频繁的使用Unity协程做一些事情,比如WWW下载、WaitForSeconds、WaitForEndOfFrame、WaitForSecondsRealtime等等
本次的教程就是教会大家如何在Lua调用Unity协程工作,xLua里有coroutine的介绍,这里就不再多说了。
上代码:
Coroutine_Runner.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using UnityEngine; using System.Collections; using System; public class Coroutine_Runner : MonoBehaviour { public void YieldAndCallback(object to_yield, Action callback) { StartCoroutine(CoBody(to_yield, callback)); } private IEnumerator CoBody(object to_yield, Action callback) { if (to_yield is IEnumerator) yield return StartCoroutine((IEnumerator)to_yield); else yield return to_yield; callback(); } } |
Coroutine.lua
1 2 3 4 5 6 7 8 9 10 11 |
local util = require 'xlua.util' local gameobject = CS.UnityEngine.GameObject('Coroutine_Runner') CS.UnityEngine.Object.DontDestroyOnLoad(gameobject) local cs_coroutine_runner = gameobject:AddComponent(typeof(CS.Coroutine_Runner)) local function async_yield_return(to_yield, cb) cs_coroutine_runner:YieldAndCallback(to_yield, cb) end yield_return = util.async_to_sync(async_yield_return) |
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function UIDelayController:OnCoroutineClick() local co = coroutine.create(function() print('coroutine start!') local s = os.time() yield_return(CS.UnityEngine.WaitForSeconds(3)) print('wait interval:', os.time() - s) local www = CS.UnityEngine.WWW('http://www.u3d8.com') yield_return(www) if not www.error then print(www.bytes) else print('error:', www.error) end end) coroutine.resume(co) end |
输出:
- 本文固定链接: http://www.u3d8.com/?p=1812
- 转载请注明: 网虫虫 在 u3d8.com 发表过