unity 资源热更新+显示进度条:根据uri下资源

实现传入uri,下载对应的资源,并且能支持多个uri的下载
例如:

        List<string> listUri = new List<string>();
        List<string> listToPath = new List<string>();
        listUri.Add(AppConst.WebUrlVideo + "/2.mp4");
        listToPath.Add(AppConst.DataPath + "/2.mp4");

        listUri.Add(AppConst.WebUrlVideo + "/3.mp4");
        listToPath.Add(AppConst.DataPath + "/3.mp4");
        DownMgr.Instance.DownResMulti(listUri, listToPath);

下载2个视频,

实现效果

这里写图片描述
这里写图片描述

DownMgr.cs 下载管理器

public void DownResMulti(List<string> listUri,List<string> listToPath,UnityEvent onDownOk = null)
    {
        DataMgr.m_isMultiDown = true;
        StartCoroutine(YieldDownResMulti(listUri, listToPath, onDownOk));
    }

    IEnumerator YieldDownResMulti(List<string> listUri,List<string> listToPath,UnityEvent onDownOk = null)
    {
        long countLength = 0;
        int cnt = 0;
        for (int i = 0; i < listUri.Count; i++)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(listUri[i]);
            request.Method = "HEAD";
            countLength += request.GetResponse().ContentLength;
            cnt++;
        }

        PrecentMgr.m_instance.m_totalLen = countLength;
        Debug.Log("总下载量:" + countLength);
        Debug.Log("下载个数:" + cnt);

        for (int i = 0; i < listUri.Count; i++)
        {
            BeginDownload(listUri[i], listToPath[i]);
            while( !(IsDownOK(listToPath[i])))
            {
                yield return new WaitForEndOfFrame();
            }
        }
        yield return new WaitForEndOfFrame();
        if (onDownOk != null)
            onDownOk.Invoke();
    }
    
   void BeginDownload(string url, string file)
    {     //线程下载
        object[] param = new object[2] { url, file };

        ThreadEvent ev = new ThreadEvent();
        ev.Key = NotiConst.UPDATE_DOWNLOAD;
        ev.evParams.AddRange(param);
        ThreadManager.Instance.AddEvent(ev, OnThreadCompleted);   //线程下载
    }

    void OnThreadCompleted(NotiData data)
    {
        switch (data.evName)
        {
            case NotiConst.UPDATE_EXTRACT:  //解压一个完成
                                            //
                break;
            case NotiConst.UPDATE_DOWNLOAD: //下载一个完成
                downloadFiles.Add(data.evParam.ToString());
                break;
        }
    }

    /// <summary>
    /// 是否下载完成
    /// </summary>
    bool IsDownOK(string file)
    {
        return downloadFiles.Contains(file);
    }

1.遍历uri,使用System.Net.HttpWebRequest得到下载的总量
2.放入线程中进行依次下载,(下载完一个再下载另一个)
3.全部下载完执行UnityEvent事件

ThreadManager.cs 下载线程

   /// <summary>
    /// 下载文件
    /// </summary>
    void OnDownloadFile(List<object> evParams) {
        string url = evParams[0].ToString();    
        currDownFile = evParams[1].ToString();

        using (WebClient client = new WebClient()) {
            sw.Start();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
            client.DownloadFileAsync(new System.Uri(url), currDownFile);
        }
    }

    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        DataMgr.m_downCur += (e.BytesReceived - m_lastDown);
        m_lastDown = e.BytesReceived;
        string value = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
        
        if (DataMgr.m_isMultiDown == false)
        {
            //下载的总量
            PrecentData preData = new PrecentData();
            preData.total = string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
            preData.precent = (float)e.BytesReceived / (float)e.TotalBytesToReceive;

            preData.speed = value;

            Loom.QueueOnMainThread((param) =>
          {
              NotificationCenter.Get().ObjDispatchEvent(KEventKey.m_evDownload, preData);
          }, null);
        }
        else if (DataMgr.m_isMultiDown == true)
        {
            Loom.QueueOnMainThread((param) =>
           {
               PrecentMgr.m_instance.UpdateMultiDown(value);
           }, null);
        }
        //正在下载显示进度
        //NotiData data = new NotiData(NotiConst.UPDATE_PROGRESS, value);
        //if (m_SyncEvent != null) m_SyncEvent(data);

        //下载一个完成
        if (e.ProgressPercentage == 100 && e.BytesReceived == e.TotalBytesToReceive) {
            sw.Reset();
            m_lastDown = 0;
            NotiData data = new NotiData(NotiConst.UPDATE_DOWNLOAD, currDownFile);
            if (m_SyncEvent != null) m_SyncEvent(data);
        }
    }

1.线程中每次取下载队列中的队头进行下载
2.使用WebClient得到当前下载文件的信息,包括当前下载速度,每一时刻下载量(传递给ui显示)
3.当当前文件下载完成时调用委托m_SyncEvent,告诉DownMgr此文件下载完,进行下一个下载uri的循环

PrecentMgr.cs 进度条显示

    public void UpdateMultiDown(string speed)
    {
        float precent = (float)DataMgr.m_downCur / (float)m_totalLen;
        m_imgPrecent.fillAmount = precent;
        string sPrecent = string.Format("{0} MB / {1} MB", (DataMgr.m_downCur / 1024d / 1024d).ToString("0.00"), (m_totalLen / 1024d / 1024d).ToString("0.00"));
        m_textSpeed.text = speed;
        m_textPrecent.text = sPrecent;
        if (precent >= 1.0f)
        {
            Destroy(gameObject);
        }
    }

根据传递过来的数据显示:百分比,下载速度,已下载量与总量

代码下载:
http://download.csdn.net/download/luoyikun/10257944

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

四夕立羽

你的鼓励将是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值