71 lines
2.5 KiB
C#
71 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Code.Infrastructure.Configs;
|
|
using Code.Infrastructure.EventBus;
|
|
using Cysharp.Threading.Tasks;
|
|
using UnityEngine;
|
|
using UnityEngine.AddressableAssets;
|
|
using UnityEngine.ResourceManagement.AsyncOperations;
|
|
|
|
namespace Code.Calendar.Constants
|
|
{
|
|
// Написать кодрайтер, который будет находить конфиги и добавлять их сюда пока написано само
|
|
public interface IConstantImagesService
|
|
{
|
|
UniTaskVoid LoadImage(ConstantImageType imageType, Action<Sprite> callback);
|
|
void ReleaseImage(ConstantImageType imageType);
|
|
}
|
|
|
|
public class ConstantImagesService : IConstantImagesService
|
|
{
|
|
private readonly EventBus _eventBus;
|
|
|
|
public Dictionary<ConstantImageType, ConstantImageConfig> Configs { get; private set; }
|
|
|
|
public ConstantImagesService(EventBus eventBus, IConfigLocator configLocator)
|
|
{
|
|
_eventBus = eventBus;
|
|
|
|
var label = configLocator.TryGetManyConfigAssetReferences<ConstantImageConfig>();
|
|
|
|
LoadImages(label).Forget();
|
|
}
|
|
|
|
private async UniTaskVoid LoadImages(string imagesLabel)
|
|
{
|
|
if ((await Addressables.LoadResourceLocationsAsync(imagesLabel).Task).Count != 0)
|
|
{
|
|
var images =
|
|
Addressables.LoadAssetsAsync<ConstantImageConfig>(imagesLabel, null, Addressables.MergeMode.Union);
|
|
|
|
await images.ToUniTask();
|
|
|
|
Configs = images.Result.ToDictionary(x=> x.imageType);
|
|
}
|
|
|
|
_eventBus.RaiseEvent<IConstantImagesServiceHandle>(x=> x.ImagesLoaded());
|
|
}
|
|
|
|
Dictionary<ConstantImageType, AsyncOperationHandle<Sprite>> _spritesHandles = new();
|
|
public async UniTaskVoid LoadImage(ConstantImageType imageType, Action<Sprite> callback)
|
|
{
|
|
if(!_spritesHandles.ContainsKey(imageType))
|
|
_spritesHandles.Add(imageType, Addressables.LoadAssetAsync<Sprite>(Configs[imageType].image));
|
|
|
|
await _spritesHandles[imageType].ToUniTask();
|
|
|
|
callback?.Invoke(_spritesHandles[imageType].Result);
|
|
}
|
|
|
|
public void ReleaseImage(ConstantImageType imageType)
|
|
{
|
|
_spritesHandles[imageType].Release();
|
|
_spritesHandles.Remove(imageType);
|
|
}
|
|
}
|
|
public interface IConstantImagesServiceHandle : IGlobalSubscriber
|
|
{
|
|
void ImagesLoaded();
|
|
}
|
|
} |