ecsy-cache
v1.0.2
Published
Cache helpers for Ecsy Entity Component System
Downloads
2
Readme
ecsy-cache
Cache helpers for Ecsy Entity Component System
Sometimes it's useful to cache Entities to be able to access them instantly from Systems by a key. This is where EntitySingleCache
and EntityMultipleCache
come handy.
To create a new cache, subclass one of these two abstract classes and define a key function key(entity:Entity):string|undefined
. Then you can call .add(entity:Entity)
and .remove(entity:Entity)
to update cache as well as get(key:string)
to fetch entities from cache by key.
The difference between Single and Multiple is that Single can only store one Entity per key and Multiple can store an array of Entities under the same key.
Usage in Systems
.add
and .remove
are defined as instance arrow functions so that they are bound to the cache instance when cache is instantiated. This enables us to pass these functions directly to .forEach
in the System:
// example execute method on a System
execute() {
this.queries.entities.added.forEach(this.world.cache.add)
this.queries.entities.removed.forEach(this.world.cache.remove)
}
Since systems are never instantiated directly but registered on the World with a constructor, it is most practical to define caches on the World and then access them in the System via world instance variable.
In order to be able to do that, we need to define ecsy's System
as System<T extends World>
. This is why ecsy-cache also provides a BaseSystem
, which is just a normal ecsy System but with generic .world instance variable (and basic .queries type definition). Then we can do something like this: src/example/ExampleWorld.test.ts
(There is some debate going on in ecsy community on how to approach Typescript type definitions. Until those debates result in a successful merge, we will be using BaseSystem
as a base class for all our systems)