UnityWebRequest下载文件

文章目录[x]
  1. 0.1:效果:
  2. 1:代码:

功能

/*
* 网速
* 进度条/百分比
* 目标文件大小(暂时没做出来)
* 当前下载大小
* 预计时间
*/

 

效果:

 

 

代码:

using System;
using System.Collections;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class DownFile : MonoBehaviour
{
    /*
     * 网速
     * 进度条/百分比
     * 目标文件大小
     * 当前下载大小
     * 预计时间
     */

    public Slider downSlider; 
    public Text downValue;

    public Text downSize;

    public Text netSpeed; 

    public Button startBtn;

    public float timer;

    public string url  = @"https://public-cdn.cloud.unitychina.cn/hub/prod/UnityHubSetup.exe";
    public string savePath = @"D:/UnityHubSetup.exe";
    void Start()
    {
        startBtn.onClick.AddListener(OnDownBtnClick);
    }



    public void OnDownBtnClick()
    {
        StartCoroutine(Down());
    }

 
    IEnumerator Down()
    {
        UnityWebRequest uwr = UnityWebRequest.Get(url);
        uwr.SendWebRequest();       
        if (uwr.isNetworkError || uwr.isHttpError)                                                    
        {
            Debug.Log(uwr.error); 
        }
        else
        {
            while (!uwr.isDone) 
            {
                downSlider.value = uwr.downloadProgress;
                downValue.text = Math.Floor(uwr.downloadProgress * 100) + "%";

                timer += Time.deltaTime;

                netSpeed.text = (uwr.downloadedBytes / 1024 / 1024.0f / timer).ToString("0.0") + "m/s";

                downSize.text =  (uwr.downloadedBytes / 1024/1024.0f).ToString("0.0") + "MB";
                yield return 0;
            }
 
            if (uwr.isDone) 
            {
                downSlider.value = 1;
                downValue.text = 100 + "%";
            }
 
           
            FileInfo file = new FileInfo(savePath);
            if (!file.Exists)
            {
                Stream sw = file.Create();
                sw.Write(uwr.downloadHandler.data, 0, uwr.downloadHandler.data.Length);
                sw.Close();
                sw.Dispose();
            }
            else
            {
                Debug.Log("已存在文件!!!");
            }
        }
    }
}

 

 

点赞

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Title - Artist
0:00