UnityWebRequestAsync.cs 1.8 KB

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