UnityWebRequestAsync.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using UnityEngine.Networking;
  3. namespace ET
  4. {
  5. public class UnityWebRequestUpdateSystem : UpdateSystem<UnityWebRequestAsync>
  6. {
  7. public override void Update(UnityWebRequestAsync self)
  8. {
  9. self.Update();
  10. }
  11. }
  12. public class UnityWebRequestAsync : Entity
  13. {
  14. public class AcceptAllCertificate: CertificateHandler
  15. {
  16. protected override bool ValidateCertificate(byte[] certificateData)
  17. {
  18. return true;
  19. }
  20. }
  21. public static AcceptAllCertificate certificateHandler = new AcceptAllCertificate();
  22. public UnityWebRequest Request;
  23. public bool isCancel;
  24. public ETTask tcs;
  25. public override void Dispose()
  26. {
  27. if (this.IsDisposed)
  28. {
  29. return;
  30. }
  31. base.Dispose();
  32. this.Request?.Dispose();
  33. this.Request = null;
  34. this.isCancel = false;
  35. }
  36. public float Progress
  37. {
  38. get
  39. {
  40. if (this.Request == null)
  41. {
  42. return 0;
  43. }
  44. return this.Request.downloadProgress;
  45. }
  46. }
  47. public ulong ByteDownloaded
  48. {
  49. get
  50. {
  51. if (this.Request == null)
  52. {
  53. return 0;
  54. }
  55. return this.Request.downloadedBytes;
  56. }
  57. }
  58. public void Update()
  59. {
  60. if (this.isCancel)
  61. {
  62. this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
  63. return;
  64. }
  65. if (!this.Request.isDone)
  66. {
  67. return;
  68. }
  69. if (!string.IsNullOrEmpty(this.Request.error))
  70. {
  71. this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
  72. return;
  73. }
  74. this.tcs.SetResult();
  75. }
  76. public async ETTask DownloadAsync(string url)
  77. {
  78. this.tcs = ETTask.Create(true);
  79. url = url.Replace(" ", "%20");
  80. this.Request = UnityWebRequest.Get(url);
  81. this.Request.certificateHandler = certificateHandler;
  82. this.Request.SendWebRequest();
  83. await this.tcs;
  84. }
  85. }
  86. }