106 lines
2.7 KiB
C#
106 lines
2.7 KiB
C#
using Godot;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using BITKit.Core.Entites;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace BITKit;
|
|
/// <summary>
|
|
/// 用于Godot的ECS.Entity实现
|
|
/// </summary>
|
|
public partial class Entity : Node,IEntity
|
|
{
|
|
/// <summary>
|
|
/// 类型组件的缓存
|
|
/// </summary>
|
|
private readonly Dictionary<Type,object> TypeComponents=new ();
|
|
/// <summary>
|
|
/// IEntityService的缓存
|
|
/// </summary>
|
|
private IEntitiesService _entitiesService;
|
|
/// <summary>
|
|
/// 所有EntityComponent
|
|
/// </summary>
|
|
private IEntityComponent[] _components;
|
|
IEntityComponent[] IEntity.Components => _components;
|
|
/// <summary>
|
|
/// IEntity.Id实现
|
|
/// </summary>
|
|
public ulong Id { get; private set; }
|
|
/// <summary>
|
|
/// 服务提供者
|
|
/// </summary>
|
|
public IServiceProvider ServiceProvider { get; private set; }
|
|
private IServiceCollection _serviceCollection;
|
|
/// <summary>
|
|
/// 加载所有EntityComponent的内部实现
|
|
/// </summary>
|
|
public override void _Ready()
|
|
{
|
|
List<IEntityComponent> entityComponents = new();
|
|
Id = GetInstanceId();
|
|
_entitiesService = DI.Get<IEntitiesService>();
|
|
|
|
_serviceCollection = new ServiceCollection();
|
|
_serviceCollection.AddLogging();
|
|
|
|
|
|
foreach (var x in MathNode.GetAllNode(this))
|
|
{
|
|
GetInstanceId();
|
|
|
|
if (x is IEntityComponent entityComponent)
|
|
{
|
|
entityComponent.BuildService(_serviceCollection);
|
|
}
|
|
|
|
foreach (var customType in x.GetType().GetCustomAttributes<CustomTypeAttribute>())
|
|
{
|
|
_serviceCollection.AddSingleton(customType.Type,x);
|
|
}
|
|
ServiceProvider = _serviceCollection.BuildServiceProvider();
|
|
|
|
if (x is not IEntityComponent component) continue;
|
|
component.Entity = this;
|
|
TypeComponents.TryAdd(component.BaseType,component);
|
|
//BIT4Log.Log<Entity>($"已加载组件:{x.Name}");
|
|
component.OnAwake();
|
|
entityComponents.Add(component);
|
|
}
|
|
foreach (var component in TypeComponents.Values.OfType<IEntityComponent>())
|
|
{
|
|
component.OnStart();
|
|
}
|
|
_entitiesService.Register(this);
|
|
this._components = entityComponents.ToArray();
|
|
SetMeta("Components",Variant.From(_components.Select(x=>x.GetType().Name).ToArray()));
|
|
}
|
|
public bool TryGetComponent<T>(out T component)
|
|
{
|
|
if (TypeComponents.TryGetValue(typeof(T), out var iComponent) && iComponent is T _component)
|
|
{
|
|
component = _component;
|
|
return true;
|
|
}
|
|
component = default;
|
|
return false;
|
|
}
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
base.Dispose(disposing);
|
|
if (disposing)
|
|
{
|
|
_entitiesService.UnRegister(this);
|
|
}
|
|
}
|
|
|
|
public bool RegisterComponent<T>(T component)
|
|
{
|
|
return TypeComponents.TryAdd(typeof(T), component);
|
|
}
|
|
|
|
|
|
}
|