UnityWebRequesterBase.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using UnityEngine.Networking;
  5. using UnityEngine;
  6. namespace YooAsset
  7. {
  8. internal abstract class UnityWebRequesterBase
  9. {
  10. protected UnityWebRequest _webRequest;
  11. protected UnityWebRequestAsyncOperation _operationHandle;
  12. // 超时相关
  13. private float _timeout;
  14. private bool _isAbort = false;
  15. private ulong _latestDownloadBytes;
  16. private float _latestDownloadRealtime;
  17. /// <summary>
  18. /// 请求URL地址
  19. /// </summary>
  20. public string URL { protected set; get; }
  21. protected void ResetTimeout(float timeout)
  22. {
  23. _timeout = timeout;
  24. _latestDownloadBytes = 0;
  25. _latestDownloadRealtime = Time.realtimeSinceStartup;
  26. }
  27. /// <summary>
  28. /// 释放下载器
  29. /// </summary>
  30. public void Dispose()
  31. {
  32. if (_webRequest != null)
  33. {
  34. _webRequest.Dispose();
  35. _webRequest = null;
  36. _operationHandle = null;
  37. }
  38. }
  39. /// <summary>
  40. /// 是否完毕(无论成功失败)
  41. /// </summary>
  42. public bool IsDone()
  43. {
  44. if (_operationHandle == null)
  45. return false;
  46. return _operationHandle.isDone;
  47. }
  48. /// <summary>
  49. /// 下载进度
  50. /// </summary>
  51. public float Progress()
  52. {
  53. if (_operationHandle == null)
  54. return 0;
  55. return _operationHandle.progress;
  56. }
  57. /// <summary>
  58. /// 下载是否发生错误
  59. /// </summary>
  60. public bool HasError()
  61. {
  62. #if UNITY_2020_3_OR_NEWER
  63. return _webRequest.result != UnityWebRequest.Result.Success;
  64. #else
  65. if (_webRequest.isNetworkError || _webRequest.isHttpError)
  66. return true;
  67. else
  68. return false;
  69. #endif
  70. }
  71. /// <summary>
  72. /// 获取错误信息
  73. /// </summary>
  74. public string GetError()
  75. {
  76. if (_webRequest != null)
  77. {
  78. return $"URL : {URL} Error : {_webRequest.error}";
  79. }
  80. return string.Empty;
  81. }
  82. /// <summary>
  83. /// 检测超时
  84. /// </summary>
  85. public void CheckTimeout()
  86. {
  87. // 注意:在连续时间段内无新增下载数据及判定为超时
  88. if (_isAbort == false)
  89. {
  90. if (_latestDownloadBytes != _webRequest.downloadedBytes)
  91. {
  92. _latestDownloadBytes = _webRequest.downloadedBytes;
  93. _latestDownloadRealtime = Time.realtimeSinceStartup;
  94. }
  95. float offset = Time.realtimeSinceStartup - _latestDownloadRealtime;
  96. if (offset > _timeout)
  97. {
  98. _webRequest.Abort();
  99. _isAbort = true;
  100. }
  101. }
  102. }
  103. }
  104. }