文章目录[x]
- 0.1:效果:
- 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("已存在文件!!!"); } } } }