Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- using Cysharp.Threading.Tasks;
- using UnityEngine;
- using UnityEngine.AddressableAssets;
- using UnityEngine.ResourceManagement.AsyncOperations;
- namespace Dre0Dru.AddressableAssets.Loaders
- {
- public class AssetsLabelLoader<TAsset> : IAssetsLoader<string, TAsset> where TAsset : Object
- {
- private readonly Dictionary<string, AsyncOperationHandle<TAsset>> _operationHandles = new();
- private readonly Dictionary<string, List<string>> _mapsLabel = new();
- public async UniTask PreloadAssetAsync(string label) => await LoadAssetAsync(label);
- public async UniTask<TAsset> LoadAssetAsync(string label)
- {
- AsyncOperationHandle<IList<TAsset>> handle = Addressables.LoadAssetsAsync<TAsset>(label, null);
- await handle.Task;
- List<string> names = new();
- // Додати елементи зі списку картинок в словник
- if (handle.Result.Count > 0)
- {
- foreach (TAsset asset in handle.Result)
- {
- names.Add(asset.name);
- _operationHandles[asset.name] = Addressables.ResourceManager
- .CreateCompletedOperation(asset, null);
- }
- }
- _mapsLabel.TryAdd(label, names);
- // Повертаємо перший елемент для прикладу, але це можна змінити залежно від вашої логіки
- return handle.Result.Count > 0 ? handle.Result[0] : null;
- }
- public bool IsAssetLoaded(string label)
- {
- if (_operationHandles.TryGetValue(label, out var handle))
- {
- return handle.Status == AsyncOperationStatus.Succeeded;
- }
- return false;
- }
- public TAsset GetAsset(string name)
- {
- if (_operationHandles.TryGetValue(name, out AsyncOperationHandle<TAsset> handle))
- {
- return handle.Result;
- }
- return null;
- }
- public bool TryGetAsset(string label, out TAsset asset)
- {
- asset = default;
- if (IsAssetLoaded(label))
- {
- asset = GetAsset(label);
- return asset;
- }
- return false;
- }
- public void UnloadAsset(string label)
- {
- if (_mapsLabel.TryGetValue(label, out List<string> assetNames))
- {
- foreach (string assetName in assetNames.ToList())
- {
- Addressables.Release(_operationHandles[assetName]);
- _operationHandles.Remove(assetName);
- }
- _mapsLabel.Remove(label);
- }
- }
- public void UnloadAllAssets()
- {
- foreach (var handle in _operationHandles.Values)
- {
- Addressables.Release(handle);
- }
- _operationHandles.Clear();
- _mapsLabel.Clear();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement