com.alicizax.unity.tuyoogam.../Runtime/DownloadSystem/Operation/Internal/UnityWebDataRequestOperation.cs

96 lines
3.1 KiB
C#
Raw Normal View History

2025-01-09 11:31:04 +08:00
using UnityEngine.Networking;
using UnityEngine;
namespace YooAsset
{
internal class UnityWebDataRequestOperation : UnityWebRequestOperation
{
2025-09-02 19:21:49 +08:00
protected enum ESteps
{
None,
CreateRequest,
Download,
Done,
}
2025-01-09 11:31:04 +08:00
private UnityWebRequestAsyncOperation _requestOperation;
2025-09-02 19:21:49 +08:00
private ESteps _steps = ESteps.None;
/// <summary>
/// 响应的超时时间单位在经过Timeout的秒数后尝试中止。
/// 注意当Timeout设置为0时不会应用超时。
/// 注意设置的超时值可能应用于Android上的每个URL重定向这可能会导致响应时间增加。
/// </summary>
private readonly int _timeout;
2025-01-09 11:31:04 +08:00
/// <summary>
/// 请求结果
/// </summary>
public byte[] Result { private set; get; }
2025-09-02 19:21:49 +08:00
internal UnityWebDataRequestOperation(string url, int timeout) : base(url)
2025-01-09 11:31:04 +08:00
{
2025-09-02 19:21:49 +08:00
_timeout = timeout;
2025-01-09 11:31:04 +08:00
}
2025-02-28 16:11:01 +08:00
internal override void InternalStart()
2025-01-09 11:31:04 +08:00
{
_steps = ESteps.CreateRequest;
}
2025-02-28 16:11:01 +08:00
internal override void InternalUpdate()
2025-01-09 11:31:04 +08:00
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.CreateRequest)
{
CreateWebRequest();
_steps = ESteps.Download;
}
if (_steps == ESteps.Download)
{
2025-09-02 19:21:49 +08:00
DownloadProgress = _webRequest.downloadProgress;
DownloadedBytes = (long)_webRequest.downloadedBytes;
2025-01-09 11:31:04 +08:00
Progress = _requestOperation.progress;
if (_requestOperation.isDone == false)
return;
if (CheckRequestResult())
{
2025-09-02 19:21:49 +08:00
var fileData = _webRequest.downloadHandler.data;
if (fileData == null || fileData.Length == 0)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"URL : {_requestURL} Download handler data is null or empty !";
}
else
{
_steps = ESteps.Done;
Result = fileData;
Status = EOperationStatus.Succeed;
}
2025-01-09 11:31:04 +08:00
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
}
// 注意:最终释放请求器
DisposeRequest();
}
}
private void CreateWebRequest()
{
DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
2025-09-02 19:21:49 +08:00
_webRequest = DownloadSystemHelper.NewUnityWebRequestGet(_requestURL);
_webRequest.timeout = _timeout;
2025-01-09 11:31:04 +08:00
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;
_requestOperation = _webRequest.SendWebRequest();
}
}
}