11using System ;
22using System . Collections . Concurrent ;
33using System . Collections . Generic ;
4- using System . Diagnostics . CodeAnalysis ;
54using System . Threading ;
65using System . Threading . Tasks ;
76
@@ -15,11 +14,11 @@ namespace EasyEcs.Core;
1514/// <br/>
1615/// You should not have multiple contexts in the same thread.
1716/// </summary>
18- [ SuppressMessage ( "ReSharper" , "SuspiciousTypeConversion.Global" ) ]
1917public partial class Context : IAsyncDisposable
2018{
2119 private readonly Random _random = new ( ) ;
2220 private readonly List < Entity > _entities = new ( ) ;
21+ private readonly Dictionary < int , Entity > _entitiesById = new ( ) ;
2322 private readonly ReaderWriterLockSlim _entitiesLock = new ( ) ;
2423 private readonly ConcurrentQueue < Entity > _removeList = new ( ) ;
2524 private readonly ConcurrentQueue < SystemBase > _runtimeAddSystemList = new ( ) ;
@@ -83,6 +82,7 @@ public Entity CreateEntity()
8382 try
8483 {
8584 _entities . Add ( entity ) ;
85+ _entitiesById . Add ( entity . Id , entity ) ;
8686 }
8787 finally
8888 {
@@ -105,6 +105,7 @@ public void DestroyEntity(Entity entity, bool immediate = false)
105105 try
106106 {
107107 _entities . Remove ( entity ) ;
108+ _entitiesById . Remove ( entity . Id ) ;
108109 }
109110 finally
110111 {
@@ -118,6 +119,17 @@ public void DestroyEntity(Entity entity, bool immediate = false)
118119 _removeList . Enqueue ( entity ) ;
119120 }
120121
122+ /// <summary>
123+ /// Get an entity by id.
124+ /// </summary>
125+ /// <param name="id"></param>
126+ /// <returns></returns>
127+ public Entity GetEntityById ( int id )
128+ {
129+ _entitiesById . TryGetValue ( id , out var entity ) ;
130+ return entity ;
131+ }
132+
121133 /// <summary>
122134 /// Get all entities.
123135 /// <br/>
@@ -200,6 +212,7 @@ public async ValueTask DisposeAsync()
200212
201213 // clear all entities
202214 _entities . Clear ( ) ;
215+ _entitiesById . Clear ( ) ;
203216 // clear all systems
204217 _executeSystems . Clear ( ) ;
205218 _initSystems . Clear ( ) ;
@@ -291,6 +304,7 @@ public async ValueTask Update(bool parallel = true)
291304 try
292305 {
293306 _entities . Remove ( entity ) ;
307+ _entitiesById . Remove ( entity . Id ) ;
294308 }
295309 finally
296310 {
0 commit comments