| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- using UnityEngine;
- using UnityEngine.Networking;
- namespace Model
- {
- [ObjectSystem]
- public class UnityWebRequestSystem : ObjectSystem<UnityWebRequestAsync>, IUpdate
- {
- public void Update()
- {
- this.Get().Update();
- }
- }
-
- public class UnityWebRequestAsync : Component
- {
- public UnityWebRequest Request;
- public bool isCancel;
- public TaskCompletionSource<bool> tcs;
-
- public override void Dispose()
- {
- if (this.IsDisposed)
- {
- return;
- }
- base.Dispose();
- this.Request?.Dispose();
- this.Request = null;
- this.isCancel = false;
- }
- public float Progress
- {
- get
- {
- if (this.Request == null)
- {
- return 0;
- }
- return this.Request.downloadProgress;
- }
- }
- public ulong ByteDownloaded
- {
- get
- {
- if (this.Request == null)
- {
- return 0;
- }
- return this.Request.downloadedBytes;
- }
- }
- public void Update()
- {
- if (this.isCancel)
- {
- this.tcs.SetResult(false);
- return;
- }
-
- if (!this.Request.isDone)
- {
- return;
- }
- if (!string.IsNullOrEmpty(this.Request.error))
- {
- this.tcs.SetException(new Exception($"request error: {this.Request.error}"));
- return;
- }
- this.tcs.SetResult(true);
- }
- public Task<bool> DownloadAsync(string url)
- {
- this.tcs = new TaskCompletionSource<bool>();
-
- url = url.Replace(" ", "%20");
- this.Request = UnityWebRequest.Get(url);
- this.Request.Send();
-
- return this.tcs.Task;
- }
- }
- }
|