UnityWebFileRequester.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine.Networking;
  5. namespace YooAsset
  6. {
  7. /// <summary>
  8. /// 下载器
  9. /// 说明:UnityWebRequest(UWR) supports reading streaming assets since 2017.1
  10. /// </summary>
  11. internal class UnityWebFileRequester
  12. {
  13. protected UnityWebRequest _webRequest;
  14. protected UnityWebRequestAsyncOperation _operationHandle;
  15. /// <summary>
  16. /// 请求URL地址
  17. /// </summary>
  18. public string URL { private set; get; }
  19. /// <summary>
  20. /// 发送GET请求
  21. /// </summary>
  22. public void SendRequest(string url, string savePath)
  23. {
  24. if (_webRequest == null)
  25. {
  26. URL = url;
  27. _webRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
  28. DownloadHandlerFile handler = new DownloadHandlerFile(savePath);
  29. handler.removeFileOnAbort = true;
  30. _webRequest.downloadHandler = handler;
  31. _webRequest.disposeDownloadHandlerOnDispose = true;
  32. _operationHandle = _webRequest.SendWebRequest();
  33. }
  34. }
  35. /// <summary>
  36. /// 释放下载器
  37. /// </summary>
  38. public void Dispose()
  39. {
  40. if (_webRequest != null)
  41. {
  42. _webRequest.Dispose();
  43. _webRequest = null;
  44. _operationHandle = null;
  45. }
  46. }
  47. /// <summary>
  48. /// 是否完毕(无论成功失败)
  49. /// </summary>
  50. public bool IsDone()
  51. {
  52. if (_operationHandle == null)
  53. return false;
  54. return _operationHandle.isDone;
  55. }
  56. /// <summary>
  57. /// 下载进度
  58. /// </summary>
  59. public float Progress()
  60. {
  61. if (_operationHandle == null)
  62. return 0;
  63. return _operationHandle.progress;
  64. }
  65. /// <summary>
  66. /// 下载是否发生错误
  67. /// </summary>
  68. public bool HasError()
  69. {
  70. #if UNITY_2020_3_OR_NEWER
  71. return _webRequest.result != UnityWebRequest.Result.Success;
  72. #else
  73. if (_webRequest.isNetworkError || _webRequest.isHttpError)
  74. return true;
  75. else
  76. return false;
  77. #endif
  78. }
  79. /// <summary>
  80. /// 获取错误信息
  81. /// </summary>
  82. public string GetError()
  83. {
  84. if (_webRequest != null)
  85. {
  86. return $"URL : {URL} Error : {_webRequest.error}";
  87. }
  88. return string.Empty;
  89. }
  90. }
  91. }