78 lines
2.3 KiB
C#
78 lines
2.3 KiB
C#
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<int, IEntity> Entities => _entities;
|
|
private readonly ConcurrentDictionary<int, IEntity> _entities = new();
|
|
private readonly IEntitiesService _entitiesService;
|
|
|
|
public EntitiesFactory(IEntitiesService entitiesService)
|
|
{
|
|
_entitiesService = entitiesService;
|
|
}
|
|
|
|
public async UniTask<IEntity> CreateAsync(string addressablePath,object model)
|
|
{
|
|
var go =await ModService.LoadAsset<GameObject>(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<string, IEntity, UniTask> OnEntityCreate;
|
|
public event Func<string, IEntity, UniTask> OnEntityCreated;
|
|
public void Dispose()
|
|
{
|
|
foreach (var (id,entity) in _entities)
|
|
{
|
|
if (entity is IDisposable disposable)
|
|
{
|
|
disposable.Dispose();
|
|
}
|
|
}
|
|
_entities.Clear();
|
|
}
|
|
}
|
|
}
|