Files
5.24BuYu/Assets/DownAddress.cs
T
2026-05-07 03:46:03 +08:00

85 lines
2.0 KiB
C#

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 XZ()
{
StartCoroutine(StartDownload());
}
public void Awake()
{
image = GetComponent<Image>();
}
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;
callback?.Invoke(handle.Result);
Addressables.Release(handle);
}
/// <summary>
/// 下载某个 Label 的所有资源
/// </summary>
public IEnumerator DownloadLabel(string label, Action<float> onProgress, Action<bool> onFinished)
{
var handle = Addressables.DownloadDependenciesAsync(label, true);
while (!handle.IsDone)
{
onProgress?.Invoke(handle.PercentComplete);
yield return null;
}
bool success = handle.Status == AsyncOperationStatus.Succeeded;
onFinished?.Invoke(success);
}
}