forked from amogus-2/Legend-of-Zelda-Recreation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Entity.cs
105 lines (85 loc) · 2.56 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using amongus3902.Components;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace amongus3902
{
internal class Entity
{
public event Action OnRemove;
public event Action OnAdd;
public readonly Dictionary<Type, IComponent> Components = new();
public readonly string UniqueID;
public Entity()
{
UniqueID = Guid.NewGuid().ToString();
}
public Entity Attach<T>(T component)
where T : IComponent
{
Type componentClass = component.GetType();
//guard to check against adding two components of the same type
Debug.Assert(!Has<T>(), $"Entity already has a component of type {componentClass}");
Components.Add(componentClass, component);
return this;
}
public Entity Detatch<T>()
where T : IComponent
{
Components.Remove(typeof(T));
return this;
}
public Entity Replace<T>(T component)
where T : IComponent
{
Detatch<T>();
Attach<T>(component);
return this;
}
public T Get<T>()
where T : IComponent
{
Debug.Assert(Has<T>(), $"Entity {UniqueID} does not have component {typeof(T)}");
return (T)Components[typeof(T)];
}
public bool Has<T>()
where T : IComponent
{
return Has(typeof(T));
}
public bool Has(Type type)
{
return Components.ContainsKey(type);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj is not Entity)
return false;
return UniqueID == ((Entity)obj).UniqueID;
}
public override int GetHashCode()
{
return UniqueID.GetHashCode();
}
public static bool operator ==(Entity left, Entity right)
{
return left.Equals(right);
}
public static bool operator !=(Entity left, Entity right)
{
return !left.Equals(right);
}
// only for the world to call, DO NOT CALL UNLESS YOU ARE WORLD
public void _remove()
{
OnRemove?.Invoke();
}
// same here probably
public void _add()
{
OnAdd?.Invoke();
}
}
}