World Entity Access
So far, we only used
ecs.Query
to access components.
Component access in queries is highly efficient, but it does not provide
access to the components of a specific entity.
This is possible through
ecs.World
methods, or using a generic MapX (like
generic.Map2
) or
generic.Map
.
Getting components
For a given entity, components can be accessed using
ecs.World.Get
or
generic.Map2.Get
, respectively:
1world := ecs.NewWorld()
2
3builder := generic.NewMap2[Position, Heading](&world)
4entity := builder.New()
5
6pos, head := builder.Get(entity)
7
8_, _ = pos, head
1world := ecs.NewWorld()
2
3posID := ecs.ComponentID[Position](&world)
4headID := ecs.ComponentID[Heading](&world)
5
6entity := world.NewEntity(posID, headID)
7
8pos := (*Position)(world.Get(entity, posID))
9head := (*Heading)(world.Get(entity, headID))
10
11_, _ = pos, head
Similarly, it is also possible to check if an entity has a given component with
ecs.World.Has
or
generic.Map.Has
, respectively:
1world := ecs.NewWorld()
2
3builder := generic.NewMap2[Position, Heading](&world)
4entity := builder.New()
5
6mapper := generic.NewMap[Position](&world)
7
8hasPos := mapper.Has(entity)
9_ = hasPos
1world := ecs.NewWorld()
2
3posID := ecs.ComponentID[Position](&world)
4headID := ecs.ComponentID[Heading](&world)
5
6entity := world.NewEntity(posID, headID)
7
8hasPos := world.Has(entity, posID)
9_ = hasPos
Note that we have to use
generic.Map
here, which is similar to
generic.Map1
for a single component, but offers more functionality.
Unchecked access
The Get
and Has
methods shown above all have a companion GetUnchecked
and HasUnchecked
,
which is faster, but should be used with care.
Particularly, they do not check whether the entity is still alive.
Like Get
, they panic when called on a removed entity.
However, for a removed and subsequently recycled entity, they lead to undefined behavior.
It is safe to use methods like
ecs.World.GetUnchecked
after a usual Get
was used on the same entity:
1world := ecs.NewWorld()
2
3posID := ecs.ComponentID[Position](&world)
4headID := ecs.ComponentID[Heading](&world)
5
6entity := world.NewEntity(posID, headID)
7
8pos := (*Position)(world.Get(entity, posID))
9head := (*Heading)(world.GetUnchecked(entity, headID))
10
11_, _ = pos, head
Note that, following this use case, generic MapX internally use
ecs.World.GetUnchecked
for all but the first component.