using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; public enum DownloadTaskState { None, Downloading, DownloadSuccess, Error, } public class DownloadTask : MonoBehaviour { private UnityWebRequest webRqst; public UnityWebRequest WebRqst { get => webRqst; } public Action Callback { get; set; } [SerializeField] public DownloadDataEntity CurDownloadEntity { get; set; } [SerializeField] public float CurLoadProgress { get; private set; } public ulong downloadSize; private float timeOut; private DownloadTaskState state; public DownloadTaskState State { get => state; private set { state = value; if (CurDownloadEntity != null) { CurDownloadEntity.State = state; } } } public ulong DownLoadSize { get => webRqst.downloadedBytes; } public DownloadTask() { //webRqst = new UnityWebRequest(); } public bool SetUrl(string url = "") { bool ret = true; if (webRqst!= null) { webRqst.Dispose(); webRqst = null; } if (string.IsNullOrEmpty(url) && CurDownloadEntity != null) { webRqst = UnityWebRequest.Get(DownloadMgr.Instance.DownloadUrl + CurDownloadEntity.FullName); } else if (!string.IsNullOrEmpty(url)) { webRqst = UnityWebRequest.Get(url); } else { ret = false; } webRqst.timeout = 5; return ret; } public void StartTask() { StartCoroutine(Task()); } public IEnumerator Task() { if (State == DownloadTaskState.Downloading) { yield break; } State = DownloadTaskState.Downloading; string savePath = DownloadMgr.Instance.LocalFilePath + CurDownloadEntity.FullName; UnityWebRequestAsyncOperation asyncOperation = webRqst.SendWebRequest(); yield return null; timeOut = Time.time; CurLoadProgress = 0; downloadSize = 0; while (!webRqst.isDone) { if (CurLoadProgress < webRqst.downloadProgress) { timeOut = Time.time; CurLoadProgress = webRqst.downloadProgress; downloadSize = webRqst.downloadedBytes; CurDownloadEntity.UpDateCallback?.Invoke(this); } if (Time.time - timeOut > DownloadMgr.TimeOut) { Debug.LogWarning("下载超时!!!"); //fs.Close(); State = DownloadTaskState.Error; Callback?.Invoke(this); yield break; } yield return null; } CurLoadProgress = webRqst.downloadProgress; downloadSize = webRqst.downloadedBytes; CurDownloadEntity.UpDateCallback?.Invoke(this); if (webRqst != null && webRqst.result == UnityWebRequest.Result.Success) { Debug.Log($"[{CurDownloadEntity.FullName}] 下载完成"); State = DownloadTaskState.DownloadSuccess; FileHelper.WirteToFile( savePath,webRqst.downloadHandler.data); Callback?.Invoke(this); } else { State = DownloadTaskState.Error; Debug.Log($"下载失败;Error = {webRqst.error} === {CurDownloadEntity.FullName} "); Callback?.Invoke(this); } webRqst.Dispose(); } }