using System; using System.Collections.Concurrent; using System.Collections.Generic; using BITKit; using BITKit.Entities; using BITKit.Mod; using Cysharp.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using UnityEngine; using Object = UnityEngine.Object; namespace Project.B.Entities { public class EntitiesFactory:IEntitiesFactory { public IReadOnlyDictionary Entities => _entities; private readonly ConcurrentDictionary _entities = new(); private readonly IEntitiesService _entitiesService; public EntitiesFactory(IEntitiesService entitiesService) { _entitiesService = entitiesService; } public async UniTask CreateAsync(string addressablePath,object model) { var go =await ModService.LoadAsset(addressablePath); go =Object.Instantiate(go); var cts = go.GetCancellationTokenOnDestroy(); var entity = new Entity(); entity.ServiceCollection.AddSingleton(new IdComponent() { Id = entity.Id = go.GetInstanceID() }); entity.ServiceCollection.AddSingleton(_entitiesService); entity.ServiceCollection.AddSingleton(go); entity.ServiceCollection.AddSingleton(go.transform); _entities.TryAdd(entity.Id, entity); cts.Register(() => { _entitiesService.UnRegister(entity); entity.Dispose(); _entities.TryRemove(entity.Id); }); await OnEntityCreate.UniTaskFunc(addressablePath,entity); await OnEntityCreated.UniTaskFunc(addressablePath,entity); _entitiesService.Register(entity); return entity; } public event Func OnEntityCreate; public event Func OnEntityCreated; public void Dispose() { foreach (var (id,entity) in _entities) { if (entity is IDisposable disposable) { disposable.Dispose(); } } _entities.Clear(); } } }