ToLua 协程中调用 WWW

来源:互联网 发布:ssl端口号 编辑:程序博客网 时间:2024/06/05 16:55

引言:

在游戏中假如需要下载网络资源,一般都是借助 Unity.WWW 工具类来完成,接下来我们分别说一下 C# 和 tolua 下实现的过程。

C# 下的实现

在 C# 中的做法通常如下:

  • 启动一个协程来执行下载任务,创建一个 WWW 对象;
  • 在一个死循环中查询下载任务是否完成;
  • 下载完成则跳出循环体,从上面创建的 WWW 对象的 bytes 属性中取出下载到的数据。
using UnityEngine;using System.Collections;public class TestWWW : MonoBehaviour {    // Use this for initialization    void Start () {        string url = "http://news.hainan.net/Editor/img/201702/20170213/big/20170213072342206_6778430.jpg";        //启动一个协程执行下载任务        StartCoroutine(Download(url));    }    IEnumerator Download(string url)    {        WWW www = new WWW(url);        //在循环中查询是否下载完毕        while (www != null)        {            if(www.isDone)            {                //下载结束退出死循环                break;            }            yield return null;        }        //统计下载数据大小        var data = www.bytes;        int strDataLengthKB = (int)data.Length / 1000;        Debug.Log("下载资源大小:"+strDataLengthKB+" KB");    }    // Update is called once per frame    void Update () {    }}

这里我已下载一张图片为例子,执行结果在如下:

下载资源大小:67 KBUnityEngine.Debug:Log(Object)

toLua 下的实现

lua 中原生的协程容易出各种奇奇怪怪的问题,tolua 中做了优化,使用起来方便得多,同样的功能在 tolua 中的写法:

coroutine.start(function()    print('协程开始')    local www = WWW('http://news.hainan.net/Editor/img/201702/20170213/big/20170213072342206_6778430.jpg')    --等待 www 下载完毕后继续执行    coroutine.www(www)    --下载到的数据    local data = www.bytes    local size = math.floor(data.Length/1000)    print('协程结束,数据大小:'..size..' Kb')end)

执行结果:

协程开始UnityEngine.Debug:Log(Object)协程结束,数据大小:67 KbUnityEngine.Debug:Log(Object)

错误判别:

我还遇到一个问题就是要下载的地址不存在,但是 WWW.bytes 依然回返回 168b 的数据,那么我们要如何来判断是否正常下载到我们想要数据?那就需要使用 WWW 自带的错误信息 WWW.error 属性了:

--错误信息local errorInfo = www.errorif errorInfo~= nil and string.len(errorInfo) > 0 then    local i,j = string.find(errorInfo,'404')    if j ~= nil then        --下载资源不存在    endend

参考资料:

  • Tolua使用笔记三:Tolua协程用法
  • 学习tolua#·20多个例子
  • Unity3D开发小贴士(十一)ToLua协同程序
  • Ulua_toLua_基本案例(五)_LuaCoroutine