-
Notifications
You must be signed in to change notification settings - Fork 0
/
Entity.cs
69 lines (60 loc) · 2.14 KB
/
Entity.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using NoNameGame.ECS.Components;
using NoNameGame.ECS.Messaging;
using System.Collections.Generic;
using System.Linq;
namespace NoNameGame.ECS.Entities
{
public abstract class Entity
{
protected readonly List<ComponentBase> _components = new List<ComponentBase>();
protected ScreenPosition _transform;
public string Name { get; set; }
public bool Destroyed { get; protected set; }
public ScreenPosition Transform
{
get
{
if (_transform == null)
{
_transform = new ScreenPosition();
_components.Add(_transform);
}
return _transform;
}
}
public bool HasComponent<TComponent>() where TComponent : ComponentBase
{
return _components.Any(x => x is TComponent);
}
public TComponent GetComponent<TComponent>() where TComponent : ComponentBase
{
return (TComponent)_components.FirstOrDefault(x => x is TComponent);
}
public TComponent AddComponent<TComponent>(TComponent component) where TComponent : ComponentBase
{
_components.Add(component);
component.Entity = this;
SystemMessageBroker.Send(new ComponentAdded<TComponent>(component, this));
return component;
}
public void RemoveComponent<TComponent>(TComponent component) where TComponent : ComponentBase
{
_components.Remove(component);
component.Entity = null;
SystemMessageBroker.Send(new ComponentRemoved<TComponent>(component, this));
}
public IEnumerable<ComponentBase> GetComponents()
{
return _components.ToList();
}
public override string ToString()
{
return $"Entity: {Name} - components: {string.Join(", ", _components.Select(x => x.GetType().ToString()))}";
}
public static void Destroy(Entity entity)
{
entity.Destroyed = true;
SystemMessageBroker.Send(new EntityDestroyed(entity));
}
}
}