using System; using System.Collections.Generic; using Cysharp.Threading.Tasks; using UnityEngine.AddressableAssets; using Object = UnityEngine.Object; namespace DanieleMarotta.RiversongCodeShowcase { [GameSystemGroup(typeof(EarlyGameSystemGroup))] [InitializeAfter(typeof(GameDatabaseSystem))] public class PreLoadAssetsSystem : GameSystem, IInitializable, IDisposable { [InjectService] private GameConfig _config; [InjectService] private IGameDatabase _gameDatabase; private readonly HashSet _loadedReferences = new(); public PreLoadAssetsSystem(IServiceLocator serviceLocator) : base(serviceLocator) { } public async UniTask InitializeAsync() { var tasks = new List(); PreLoadAgents(tasks); PreLoadProducts(tasks); PreLoadBuildings(tasks); await UniTask.WhenAll(tasks); } private void PreLoadAgents(List tasks) { Load(_config.Agents.GenericAgent, tasks); Load(_config.Agents.HunterAgent, tasks); Load(_config.Agents.FarmerAgent, tasks); } private void PreLoadProducts(List tasks) { foreach (var product in _gameDatabase.OfType()) { Load(product.ProductStackVisualization, tasks); Load(product.CarriedVisualization, tasks); } } private void PreLoadBuildings(List tasks) { Load(_config.Population.TentBuilding, tasks); foreach (var building in _gameDatabase.OfType()) Load(building.Visualization, tasks); } private void Load(AssetReferenceT assetReference, List tasks) where T : Object { if (!assetReference.RuntimeKeyIsValid() || !_loadedReferences.Add(assetReference)) return; tasks.Add(assetReference.LoadAssetAsync().ToUniTask()); } public void Dispose() { foreach (var assetReference in _loadedReferences) assetReference.ReleaseAsset(); } } }