This commit is contained in:
CortexCore 2024-08-14 12:22:08 +08:00
parent 79985ad6f5
commit 056e2cada5
2 changed files with 94 additions and 0 deletions

92
Src/Core/ECS/Entity.cs Normal file
View File

@ -0,0 +1,92 @@
using System;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
namespace BITKit.Entities
{
public class Entity : IEntity, IDisposable
{
public Entity()
{
RegisterComponent<IEntity>(this);
}
public void WaitForInitializationComplete()
{
throw new NotImplementedException();
}
public int Id { get; set; } = Guid.NewGuid().GetHashCode();
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
private readonly CancellationTokenSource _cancellationTokenSource = new();
public bool TryGetComponent<T>(out T component)
{
var value = ServiceProvider.GetService<T>();
if (value != null)
{
component = value;
return true;
}
component = default!;
return false;
}
public bool TryGetComponent(Type type, out IEntityComponent component)
{
var value = ServiceProvider.GetService(type);
if (value != null)
{
component = (IEntityComponent)value;
return true;
}
component = default!;
return false;
}
public IEntityComponent[] Components => ServiceCollection.OfType<IEntityComponent>().ToArray();
public bool RegisterComponent<T>(T component)
{
_services.Add(component);
ServiceCollection.AddSingleton(typeof(T), component);
return true;
}
public IServiceProvider ServiceProvider => _serviceProvider ??= ServiceCollection.BuildServiceProvider();
public IServiceCollection ServiceCollection { get; } = new ServiceCollection();
private IServiceProvider _serviceProvider;
private readonly CacheList<object> _services = new();
public object[] GetServices()
{
return _services.ToArray();
}
public void Inject(object obj)
{
foreach (var fieldInfo in obj.GetType().GetFields(ReflectionHelper.Flags))
{
if (Attribute.IsDefined(fieldInfo, typeof(InjectAttribute)))
{
fieldInfo.SetValue(obj, ServiceProvider.GetService(fieldInfo.FieldType));
}
}
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
foreach (var service in _services)
{
if (service is IDisposable disposable)
{
disposable.Dispose();
}
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 881c97aa8732ace4796d97874c8f8769