Files
5.24BuYu/Assets/DownAddress.cs
T
2026-03-18 17:26:14 +08:00

61 lines
2.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
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(Starta());
}
IEnumerator Starta()
{
// 1. 先检查需要下载的大小
AsyncOperationHandle<long> checkSizeHandle = Addressables.GetDownloadSizeAsync(preloadLabel);
yield return checkSizeHandle;
if (checkSizeHandle.Result > 0)
{
Debug.Log($"需要下载 {checkSizeHandle.Result} 字节");
// 2. 开始下载
AsyncOperationHandle downloadHandle = Addressables.DownloadDependenciesAsync(preloadLabel, true); // autoReleaseHandle 设为 true
// 等待下载完成,并可选择性地更新进度
while (!downloadHandle.IsDone)
{
// 使用 GetDownloadStatus() 可以获取更精确的下载状态
DownloadStatus status = downloadHandle.GetDownloadStatus();
float percent = status.Percent * 100;
Debug.Log($"下载进度: {percent:F1}%");
image.fillAmount =1-status.Percent;
yield return null;
}
// 3. 检查结果
if (downloadHandle.Status == AsyncOperationStatus.Succeeded)
{
Debug.Log("预下载完成!");
}
else
{
Debug.LogError("预下载失败!");
}
// 因为我们传入了 autoReleaseHandle = true,所以不需要手动调用 downloadHandle.Release()
}
else
{
Debug.Log("所有资源已是最新,无需下载。");
}
// 记得释放检查大小的操作句柄
Addressables.Release(checkSizeHandle);
}
}