Files
Hasebe/Assets/Code/Infrastructure/Volume/VolumeFactory.cs
T
2026-09-20 15:26:03 +03:00

76 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Code.Infrastructure.Configs;
using Code.Infrastructure.Utils;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using Object = UnityEngine.Object;
namespace Code.Infrastructure.Volume
{
public interface IVolumeFactory
{
UniTask<UnityEngine.Rendering.Volume> LoadVolume(VolumeId volumeId, Transform transform = null);
void ReleaseVolume(UnityEngine.Rendering.Volume volume);
}
public interface IVolumeFactoryInitializer
{
UniTask LoadConfigs();
}
public class VolumeFactory : IDisposable, IVolumeFactory, IVolumeFactoryInitializer
{
private Dictionary<VolumeId, VolumeSettings> _configs;
private AsyncOperationHandle<IList<VolumeSettings>> _configsHandle;
private string _configsLabel;
public VolumeFactory(IConfigLocator configLocator)
{
_configsLabel = configLocator.TryGetManyConfigAssetReferences<VolumeSettings>();
}
public async UniTask LoadConfigs()
{
if(!await AddressablesUtilities.CheckLabelExists(_configsLabel))
{
_configs = new();
return;
}
_configsHandle = Addressables.LoadAssetsAsync<VolumeSettings>(_configsLabel);
await _configsHandle.ToUniTask();
_configs = _configsHandle.Result.ToDictionary(c => c.id);
}
public async UniTask<UnityEngine.Rendering.Volume> LoadVolume(VolumeId volumeId, Transform transform = null)
{
UnityEngine.Rendering.Volume volume = !transform
? (await Addressables.InstantiateAsync(_configs[volumeId].prefab, transform).ToUniTask())
.GetComponent<UnityEngine.Rendering.Volume>()
: (await Addressables.InstantiateAsync(_configs[volumeId].prefab).ToUniTask())
.GetComponent<UnityEngine.Rendering.Volume>();
if(_configs[volumeId].doNotDestroyOnLoad)
Object.DontDestroyOnLoad(volume.gameObject);
return volume;
}
public void ReleaseVolume(UnityEngine.Rendering.Volume volume)
{
Addressables.ReleaseInstance(volume.gameObject);
}
public void Dispose()
{
if(_configsHandle.IsValid()) Addressables.Release(_configsHandle);
}
}
}