Files
5.24BuYu/Assets/DownAddress.cs
T

100 lines
2.3 KiB
C#
Raw Normal View History

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