Unity UnityWebRequest下载文件 替代WWW

版权声明:辛辛苦苦写的,转载请注明出处噢 https://blog.csdn.net/wangjiangrong/article/details/80914171

今天测试那边提了个问题,就是当网络极差的时候,游戏下载将会停止(即一直在等待yield return www)当时间较长时网络恢复将无法继续下载,也没有提示,需要重启才能重新下载。因为WWW不存在设置timeout属性,因此当我们网络不好请求超时的时候,无法简单的做出判断。后面查阅资料发现Unity早在5.4版本的时候就出了新的API UnityWebRequest用于替代WWW。这边就简单的记录下UnityWebRequest的使用方法。

注:本文是在之前文章Unity 下载文件 WWW与HttpWebRequest 断点续传的基础下,添加的测试代码。所以有兴趣的同学要先看一下前文。

直接上代码,我们在DownTool.cs中添加一个新的Item,WebRequestDownloadItem

/// <summary>
/// UnityWebRequest的方式下载
/// </summary>
public class WebRequestDownloadItem : DownloadItem {

    UnityWebRequest m_webRequest;

    public WebRequestDownloadItem(string url, string path) : base(url, path) {

    }

    public override void StartDownload(Action callback = null) {
        base.StartDownload();
        UICoroutine.instance.StartCoroutine(Download(callback));
    }

    IEnumerator Download(Action callback = null) {
        m_webRequest = UnityWebRequest.Get(m_srcUrl);
        m_isStartDownload = true;
        m_webRequest.timeout = 30;//设置超时,若m_webRequest.SendWebRequest()连接超时会返回,且isNetworkError为true
        yield return m_webRequest.SendWebRequest();
        m_isStartDownload = false;

        if(m_webRequest.isNetworkError) {
            Debug.Log("Download Error:" + m_webRequest.error);
        } else {
            byte[] bytes = m_webRequest.downloadHandler.data;
            //创建文件
            FileTool.CreatFile(m_saveFilePath, bytes);
        }

        if(callback != null) {
            callback();
        }
    }

    public override float GetProcess() {
        if(m_webRequest != null) {
            return m_webRequest.downloadProgress;
        }
        return 0;
    }

    public override long GetCurrentLength() {
        if(m_webRequest != null) {
            return (long)m_webRequest.downloadedBytes;
        }
        return 0;
    }

    public override long GetLength() {
        return 0;
    }

    public override void Destroy() {
        if(m_webRequest != null) {
            m_webRequest.Dispose();
            m_webRequest = null;
        }
    }
}


使用如下,在DownloadDemo的Start方法中初始化即可

m_item = new WebRequestDownloadItem(testScrUrl, Application.persistentDataPath);
m_item.StartDownload(DownloadFinish);


因为可以设置timeout时间,所以当网络不好连接超时的时候,yield return就会往下执行,并且给出error提示,我们就可以根据错误提醒玩家进行后续的操作。

UnityWebRequest,除了从服务器下载数据(downloadHandler),同样可以将数据发送到服务器(uploadHandler)以后补充。

猜你喜欢

转载自blog.csdn.net/wangjiangrong/article/details/80914171
今日推荐