DragonECS-Unity/src/Connectors/EcsEntityConnect.cs

88 lines
2.4 KiB
C#
Raw Normal View History

2023-05-07 00:50:44 +08:00
using System.Runtime.CompilerServices;
using UnityEngine;
namespace DCFApixels.DragonECS
{
public class EcsEntityConnect : MonoBehaviour
{
2023-06-22 14:30:03 +08:00
private sealed class Aspect : EcsAspect
2023-05-07 00:50:44 +08:00
{
public readonly EcsPool<UnityGameObject> unityGameObjects;
2023-06-22 14:30:03 +08:00
public Aspect(Builder b)
2023-05-07 00:50:44 +08:00
{
unityGameObjects = b.Include<UnityGameObject>();
}
}
private entlong _entity;
private EcsWorld _world;
[SerializeField]
2024-03-03 03:51:49 +08:00
private ScriptableEntityTemplate[] _scriptableTemplates;
2023-05-07 00:50:44 +08:00
[SerializeField]
2024-03-03 03:51:49 +08:00
private MonoEntityTemplate[] _monoTemplates;
2023-05-07 00:50:44 +08:00
2024-03-03 03:51:49 +08:00
internal void SetTemplates_Editor(MonoEntityTemplate[] tempaltes)
2023-05-07 00:50:44 +08:00
{
2024-03-03 03:51:49 +08:00
_monoTemplates = tempaltes;
2023-05-07 00:50:44 +08:00
}
#region Properties
public entlong Entity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _entity;
}
public EcsWorld World
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _world;
}
2024-03-03 03:51:49 +08:00
public bool IsConected
2023-05-07 00:50:44 +08:00
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _entity.IsAlive;
}
#endregion
public void ConnectWith(entlong entity, bool applyTemplates = false)
{
2023-06-22 14:40:26 +08:00
if (_entity.TryGetID(out int oldE) && _world != null)
2023-05-07 00:50:44 +08:00
{
2023-06-22 14:30:03 +08:00
var s = _world.GetAspect<Aspect>();
2023-05-07 00:50:44 +08:00
s.unityGameObjects.Del(oldE);
}
_world = null;
if (entity.TryGetID(out int newE))
{
_entity = entity;
_world = _entity.World;
2023-06-22 14:30:03 +08:00
var s = _world.GetAspect<Aspect>();
2023-05-07 00:50:44 +08:00
if (!s.unityGameObjects.Has(newE)) s.unityGameObjects.Add(newE) = new UnityGameObject(gameObject);
if (applyTemplates)
ApplyTemplates();
}
else
{
_entity = entlong.NULL;
}
}
2024-03-03 03:51:49 +08:00
public void ApplyTemplates()
{
ApplyTemplatesFor(_entity.ID);
}
2023-05-07 00:50:44 +08:00
public void ApplyTemplatesFor(int entityID)
{
2024-03-03 03:51:49 +08:00
foreach (var t in _scriptableTemplates)
{
t.Apply(_world.id, entityID);
}
foreach (var t in _monoTemplates)
{
t.Apply(_world.id, entityID);
}
2023-05-07 00:50:44 +08:00
}
}
2024-03-06 21:37:21 +08:00
}