DownloaderBase.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. 
  2. namespace YooAsset
  3. {
  4. internal abstract class DownloaderBase
  5. {
  6. protected enum ESteps
  7. {
  8. None,
  9. CheckLocalFile,
  10. CreateDownload,
  11. CheckDownload,
  12. TryAgain,
  13. Succeed,
  14. Failed,
  15. }
  16. protected readonly BundleInfo _bundleInfo;
  17. protected ESteps _steps = ESteps.None;
  18. protected int _timeout;
  19. protected int _failedTryAgain;
  20. protected int _requestCount;
  21. protected string _requestURL;
  22. protected string _lastError = string.Empty;
  23. protected float _downloadProgress = 0f;
  24. protected ulong _downloadedBytes = 0;
  25. /// <summary>
  26. /// 下载进度
  27. /// </summary>
  28. public float DownloadProgress
  29. {
  30. get { return _downloadProgress; }
  31. }
  32. /// <summary>
  33. /// 已经下载的总字节数
  34. /// </summary>
  35. public ulong DownloadedBytes
  36. {
  37. get { return _downloadedBytes; }
  38. }
  39. public DownloaderBase(BundleInfo bundleInfo)
  40. {
  41. _bundleInfo = bundleInfo;
  42. }
  43. public void SendRequest(int failedTryAgain, int timeout)
  44. {
  45. if (_steps == ESteps.None)
  46. {
  47. _failedTryAgain = failedTryAgain;
  48. _timeout = timeout;
  49. _steps = ESteps.CheckLocalFile;
  50. }
  51. }
  52. public abstract void Update();
  53. public abstract void Abort();
  54. /// <summary>
  55. /// 获取网络请求地址
  56. /// </summary>
  57. protected string GetRequestURL()
  58. {
  59. // 轮流返回请求地址
  60. _requestCount++;
  61. if (_requestCount % 2 == 0)
  62. return _bundleInfo.RemoteFallbackURL;
  63. else
  64. return _bundleInfo.RemoteMainURL;
  65. }
  66. /// <summary>
  67. /// 获取资源包信息
  68. /// </summary>
  69. public BundleInfo GetBundleInfo()
  70. {
  71. return _bundleInfo;
  72. }
  73. /// <summary>
  74. /// 检测下载器是否已经完成(无论成功或失败)
  75. /// </summary>
  76. public bool IsDone()
  77. {
  78. return _steps == ESteps.Succeed || _steps == ESteps.Failed;
  79. }
  80. /// <summary>
  81. /// 下载过程是否发生错误
  82. /// </summary>
  83. public bool HasError()
  84. {
  85. return _steps == ESteps.Failed;
  86. }
  87. /// <summary>
  88. /// 按照错误级别打印错误
  89. /// </summary>
  90. public void ReportError()
  91. {
  92. YooLogger.Error(GetLastError());
  93. }
  94. /// <summary>
  95. /// 按照警告级别打印错误
  96. /// </summary>
  97. public void ReportWarning()
  98. {
  99. YooLogger.Warning(GetLastError());
  100. }
  101. /// <summary>
  102. /// 获取最近发生的错误信息
  103. /// </summary>
  104. public string GetLastError()
  105. {
  106. return $"Failed to download : {_requestURL} Error : {_lastError}";
  107. }
  108. }
  109. }