Resources
Resources are singular data structures in an ECS world. As such, they can be thought of as components that exist only once and are not associated to an entity. Examples could be the current game/simulation tick, a grid that your entities live on, or an acceleration structure for spatial indexing.
A world can contain up to 256 resources (64 with build tag tiny
).
Adding resources
Resources are Go structs that can contain any types of variables, just like components.
Simply instantiate your resource and add a pointer to it to the world using ecs.AddResource
,
typically during world initialization:
1// Create a resource.
2var worldGrid Grid = NewGrid(100, 100)
3// Add it to the world.
4ecs.AddResource(&world, &worldGrid)
The original resource struct can be stored and modified, and changes are reflected in code that retrieves the resource from the world (see the following sections).
Direct access
Resources can be retrieved from the world by their type, with ecs.GetResource
:
1// Get a resource from the world.
2grid := ecs.GetResource[Grid](&world)
3_ = grid
However, this method has an overhead of approx. 20ns for the type lookup. It is sufficient for one-time use of a resource. When accessing a resource regularly, Resource mappers should be used.
Resource mappers
Resource mappers are a more efficient way for retrieving a resource repeatedly.
To use them, create an ecs.Resource
, store it, and use it for retrieval:
1// In your system, create a resource mapper.
2// Store it permanently and reuse it for best performance.
3gridRes := ecs.NewResource[Grid](&world)
4
5// Access the resource.
6grid := gridRes.Get()
7_ = grid
This way, resource access takes less than 1ns.
Resource mappers can also be used the add and remove resources, and to check for their existence:
1// In your system, create a resource mapper.
2// Store it permanently and reuse it for best performance.
3gridRes := ecs.NewResource[Grid](&world)
4
5// Check for existence of the resource.
6if gridRes.Has() {
7 // Remove the resource if it exists.
8 gridRes.Remove()
9} else {
10 // Add a new one otherwise.
11 grid := NewGrid(100, 100)
12 gridRes.Add(&grid)
13}