-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
EntityExtension.cs
70 lines (59 loc) · 1.96 KB
/
EntityExtension.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
using System.Collections.Generic;
namespace DefaultEcs.Children
{
public static class EntityExtension
{
private readonly struct Children
{
public readonly HashSet<Entity> Value;
public Children(HashSet<Entity> value)
{
Value = value;
}
}
private static readonly HashSet<World> _worlds = new();
private static void OnEntityDisposed(in Entity entity)
{
if (entity.Has<Children>())
{
HashSet<Entity> children = entity.Get<Children>().Value;
entity.Remove<Children>();
foreach (Entity child in children)
{
if (child.IsAlive)
{
child.Dispose();
}
}
}
}
public static void SetAsParentOf(this Entity parent, Entity child)
{
if (_worlds.Add(parent.World))
{
parent.World.SubscribeEntityDisposed(OnEntityDisposed);
parent.World.SubscribeWorldDisposed(w => _worlds.Remove(w));
}
HashSet<Entity> children;
if (!parent.Has<Children>())
{
children = new HashSet<Entity>();
parent.Set(new Children(children));
}
else
{
children = parent.Get<Children>().Value;
}
children.Add(child);
}
public static void RemoveFromParentsOf(this Entity parent, Entity child)
{
if (parent.Has<Children>())
{
parent.Get<Children>().Value.Remove(child);
}
}
public static void SetAsChildOf(this Entity child, Entity parent) => parent.SetAsParentOf(child);
public static void RemoveFromChildrenOf(this Entity child, Entity parent) => parent.RemoveFromParentsOf(child);
}
}