-
Notifications
You must be signed in to change notification settings - Fork 0
/
SingletonByNameSystem.cs
95 lines (76 loc) · 3.27 KB
/
SingletonByNameSystem.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
using System;
using Leopotam.EcsLite;
using Leopotam.EcsLite.Di;
namespace Gemserk.Leopotam.Ecs
{
public class SingletonByNameSystem : BaseSystem, IEcsRunSystem, IEntityCreatedHandler, IEntityDestroyedHandler
{
readonly EcsPoolInject<NameComponent> names = default;
public void OnEntityCreated(World world, Entity entity)
{
var names = this.names.Value;
if (!names.Has(entity))
{
return;
}
var nameComponent = names.Get(entity);
if (!nameComponent.singleton)
return;
var singletonByNameEntities = world.sharedData.singletonByNameEntities;
if (singletonByNameEntities.ContainsKey(nameComponent.name))
{
var oldEntity = singletonByNameEntities[nameComponent.name];
if (oldEntity != entity)
{
throw new Exception($"Can't have two entities with same name {nameComponent.name}");
}
}
singletonByNameEntities[nameComponent.name] = entity;
nameComponent.cachedInSingletonsDictionary = true;
}
public void OnEntityDestroyed(World world, Entity entity)
{
var names = this.names.Value;
if (!names.Has(entity))
{
return;
}
ref var nameComponent = ref names.Get(entity);
if (nameComponent.singleton)
{
var singletonByNameEntities = world.sharedData.singletonByNameEntities;
singletonByNameEntities.Remove(nameComponent.name);
}
nameComponent.name = null;
nameComponent.singleton = false;
nameComponent.cachedInSingletonsDictionary = false;
}
public void Run(EcsSystems systems)
{
var nameComponents = world.GetComponents<NameComponent>();
foreach (var entity in world.GetFilter<NameComponent>().End())
{
ref var nameComponent = ref nameComponents.Get(entity);
// Having a singleton name component to have a null or empty name should be an error.
if (string.IsNullOrEmpty(nameComponent.name))
{
continue;
}
if (!nameComponent.cachedInSingletonsDictionary && nameComponent.singleton)
{
var singletonByNameEntities = world.sharedData.singletonByNameEntities;
if (singletonByNameEntities.ContainsKey(nameComponent.name))
{
var oldEntity = singletonByNameEntities[nameComponent.name];
if (oldEntity != entity)
{
throw new Exception($"Can't have two entities with same name {nameComponent.name}");
}
}
singletonByNameEntities[nameComponent.name] = this.GetEntity(entity);
nameComponent.cachedInSingletonsDictionary = true;
}
}
}
}
}