UnityWebRequestAsync.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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, IUpdate
  13. {
  14. public static AcceptAllCertificate certificateHandler = new AcceptAllCertificate();
  15. public UnityWebRequest Request;
  16. public bool isCancel;
  17. public ETTask tcs;
  18. public override void Dispose()
  19. {
  20. if (this.IsDisposed)
  21. {
  22. return;
  23. }
  24. base.Dispose();
  25. this.Request?.Dispose();
  26. this.Request = null;
  27. this.isCancel = false;
  28. }
  29. public float Progress
  30. {
  31. get
  32. {
  33. if (this.Request == null)
  34. {
  35. return 0;
  36. }
  37. return this.Request.downloadProgress;
  38. }
  39. }
  40. public ulong ByteDownloaded
  41. {
  42. get
  43. {
  44. if (this.Request == null)
  45. {
  46. return 0;
  47. }
  48. return this.Request.downloadedBytes;
  49. }
  50. }
  51. public void Update()
  52. {
  53. if (this.isCancel)
  54. {
  55. this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
  56. return;
  57. }
  58. if (!this.Request.isDone)
  59. {
  60. return;
  61. }
  62. if (!string.IsNullOrEmpty(this.Request.error))
  63. {
  64. this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
  65. return;
  66. }
  67. this.tcs.SetResult();
  68. }
  69. public async ETTask DownloadAsync(string url)
  70. {
  71. this.tcs = ETTask.Create(true);
  72. url = url.Replace(" ", "%20");
  73. this.Request = UnityWebRequest.Get(url);
  74. this.Request.certificateHandler = certificateHandler;
  75. this.Request.SendWebRequest();
  76. await this.tcs;
  77. }
  78. }
  79. }