1
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.AddressableAssets;
|
||||
using UnityEngine.ResourceManagement.AsyncOperations;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class DownAddress : MonoBehaviour
|
||||
{
|
||||
public string preloadLabel = "XJMH";
|
||||
public Image image;
|
||||
|
||||
public void Awake()
|
||||
{
|
||||
image = GetComponent<Image>();
|
||||
}
|
||||
|
||||
public void XZ()
|
||||
{
|
||||
StartCoroutine(StartDownload());
|
||||
}
|
||||
|
||||
IEnumerator StartDownload()
|
||||
{
|
||||
// 1. 获取大小
|
||||
long size = 0;
|
||||
yield return DownloadManager.Instance.GetSize(preloadLabel, s => size = s);
|
||||
|
||||
if (size <= 0)
|
||||
{
|
||||
Debug.Log("无需下载");
|
||||
yield break;
|
||||
}
|
||||
|
||||
Debug.Log($"需要下载 {size / 1024f / 1024f:F2} MB");
|
||||
|
||||
// 2. 下载
|
||||
yield return DownloadManager.Instance.DownloadLabel(
|
||||
preloadLabel,
|
||||
progress =>
|
||||
{
|
||||
image.fillAmount = progress;
|
||||
},
|
||||
success =>
|
||||
{
|
||||
Debug.Log(success ? "下载完成" : "下载失败");
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class DownloadManager : Singleton<DownloadManager>
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取某个 Label 的下载大小(字节)
|
||||
/// </summary>
|
||||
public IEnumerator GetSize(string label, Action<long> callback)
|
||||
{
|
||||
var handle = Addressables.GetDownloadSizeAsync(label);
|
||||
yield return handle;
|
||||
|
||||
long size = 0;
|
||||
|
||||
if (handle.Status == AsyncOperationStatus.Succeeded)
|
||||
size = handle.Result;
|
||||
else
|
||||
Debug.LogError($"GetSize 失败:{label}");
|
||||
|
||||
callback?.Invoke(size);
|
||||
|
||||
Addressables.Release(handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 下载某个 Label 的所有资源
|
||||
/// </summary>
|
||||
public IEnumerator DownloadLabel(string label, Action<float> onProgress, Action<bool> onFinished)
|
||||
{
|
||||
// 不要自动释放
|
||||
var handle = Addressables.DownloadDependenciesAsync(label, false);
|
||||
|
||||
while (!handle.IsDone)
|
||||
{
|
||||
onProgress?.Invoke(handle.PercentComplete);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
bool success = handle.Status == AsyncOperationStatus.Succeeded;
|
||||
|
||||
if (!success)
|
||||
Debug.LogError($"下载失败:{label}");
|
||||
|
||||
onFinished?.Invoke(success);
|
||||
|
||||
Addressables.Release(handle);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user