UnityWebRequestAsync.cs 1.5 KB

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