using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using System;
using System.Collections.Generic;
using System.Collections;
using Unity.VisualScripting;
using UnityEngine.Serialization;
public class AssetLoader : UnitySingleton<AssetLoader>
{
public Dictionary<string, Stack<AsyncOperationHandle>> _assetHandles = new Dictionary<string, Stack<AsyncOperationHandle>>();
public void Awake()
{
}
// 加载资源的方法
public void LoadAsset<T>(string assetKey, Action<T> onAssetLoaded = null)
{
var handle = Addressables.LoadAssetAsync<T>(assetKey);
handle.Completed += (operationHandle) =>
{
if (operationHandle.Status == AsyncOperationStatus.Succeeded)
{
_assetHandles.TryGetValue(assetKey, out var handles);
if (handles == null)
{
handles = new Stack<AsyncOperationHandle>();
_assetHandles.Add(assetKey, handles);
}
handles.Push(operationHandle);
onAssetLoaded?.Invoke(operationHandle.Result);
}
else
{
Debug.LogError("Failed to load asset: " + operationHandle.DebugName);
}
// Ensure the handle is removed from the dictionary even if an exception occurred.
};
}
public AsyncOperationHandle LoadAssetReturnHandle<T>(string assetKey, Action<T> onAssetLoaded)
{
var handle = Addressables.LoadAssetAsync<T>(assetKey);
handle.Completed += (operationHandle) =>
{
if (operationHandle.Status == AsyncOperationStatus.Succeeded)
{
onAssetLoaded?.Invoke(operationHandle.Result);
}
else
{
Debug.LogError("Failed to load asset: " + operationHandle.OperationException);
}
// Ensure the handle is removed from the dictionary even if an exception occurred.
};
return handle;
}
// 释放指定的单个资源
public void ReleaseAsset(string assetKey)
{
_assetHandles.TryGetValue(assetKey, out var handles);
if (handles == null)
return;
if (handles.Count > 0)
{
var handle = handles.Pop();
if (handle.IsValid())
{
ReleaseAsset(handle);
_assetHandles.Remove(assetKey);
}
}
}
public void ReleaseAsset(AsyncOperationHandle handle)
{
Addressables.Release(handle);
}
// 释放所有加载的资源
public void ReleaseAllAssets()
{
}
// 在 MonoBehaviour 的 OnDisable 或 OnDestroy 方法中释放资源
void OnDisable()
{
ReleaseAllAssets();
}
}
unity中对Addressable进行资源加载封装
于 2024-08-28 16:21:25 首次发布