Files
test/Assets/PerfectWorld/Scripts/Addressable/AddressableManager.cs
T
2025-10-22 16:34:56 +07:00

64 lines
2.1 KiB
C#

using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceLocations;
namespace BrewMonster.Scripts
{
public class AddressableManager : MonoSingleton<AddressableManager>
{
private bool _isInitialized = false;
private Dictionary<string, AsyncOperationHandle<GameObject>> _loadedAssets = new();
protected override void Initialize()
{
base.Initialize();
_isInitialized = false;
Addressables.InitializeAsync().Completed += OnInitializeComplete;
}
void OnInitializeComplete(AsyncOperationHandle<IResourceLocator> handle)
{
if (handle.Status == AsyncOperationStatus.Succeeded)
{
_isInitialized = true;
}
else
{
// print out the error
BMLogger.LogError($"AddressableManager: Failed to initialize: {handle.OperationException?.Message} {handle.OperationException?.StackTrace}");
}
}
/// <summary>
/// Load an asset asynchronously. The address should look like this: "models/npcs/npc/魅灵首领/魅灵首领/魅灵首领.prefab"
/// </summary>
/// <returns></returns>
public async Task<GameObject> LoadPrefabAsync(string assetPath)
{
if (_loadedAssets.ContainsKey(assetPath))
{
return _loadedAssets[assetPath].Result;
}
var handle = Addressables.LoadAssetAsync<GameObject>(assetPath);
await handle.Task;
_loadedAssets[assetPath] = handle;
return handle.Result;
}
/// <summary>
/// When the asset is no longer needed, call this method to unload it.
/// </summary>
/// <param name="assetPath"></param>
public void UnloadAsset(string assetPath)
{
Addressables.Release(assetPath);
}
}
}