Becsy provides built-in types for managing relationships between entities. Never reference entities via IDs or by storing Entity objects in Type.object properties.
Type.ref
Used for 1-to-1 relationships. A Type.ref field holds a reference to a single entity or null.
- If the target entity is deleted, the reference is automatically nulled out.
- The previous value remains accessible via
System.accessRecentlyDeletedData until overwritten or purged.
Type.backrefs
Used for 1-to-N relationships. A Type.backrefs field automatically maintains a list of references to the entity where the component resides.
- The list is managed automatically by Becsy; it cannot be modified manually.
- The order of entities in the list is arbitrary.
- Configuration Options:
- Default: Includes all references to the entity (cheapest).
- Component Type: Only includes references from components of a specific type.
- Component Type + Field Name: Only includes references from a specific field within a specific component type (safest/most precise).
Note on Writes: A system modifying ref properties implicitly requires write entitlements to all component types that have backrefs pointing to that entity, as those lists will change.
N-to-N Relationships
To model N-to-N relationships (like friendships), you must reify the relationship as its own entity containing Type.ref fields.
// Example: 1-to-N relationship (Inventory)
@component class Packed {
@field.ref declare holder: Entity;
}
@component class Inventory {
@field.backrefs(Packed, 'holder') declare contents: Entity[];
}
world.build(sys => {
const player = sys.createEntity(Inventory, Health);
const potion = sys.createEntity(Potion, {healing: 200});
// Add item to player's inventory
potion.add(Packed, {holder: player});
// Access contents
const items = player.read(Inventory).contents; // [potion]
// Remove item
potion.remove(Packed);
player.read(Inventory).contents; // []
});