bevy_many_relationships
A Bevy plugin for many-to-many relationships between entities.
Bevy's built-in Relationship trait supports one-to-one relationships (each entity has at most one component of a given relationship type). Many game mechanics require many-to-many: a character knows many NPCs, an NPC is known by many characters. This library provides that.
Concepts
OutgoingRelationships<R>storessource -> targetedges for relationship payload typeR.IncomingRelationships<R>stores the reverse index of sources for each target.add_*methods are insert-only (existing payload is preserved).set_*methods are upsert/overwrite.- Entity command methods are deferred, so usage is: queue commands, then
flush/apply_deferred, then query or react via events.
Usage
Define a relationship type as a plain unit struct:
;
Enable the plugin:
Add and remove relationships via entity commands:
Marker-style relationships (unit structs)
Use a unit struct when you only care that an edge exists.
;
commands
.entity
.;
Payload relationships (metadata per edge)
Use any payload struct to attach data directly to each source -> target edge.
commands
.entity
.;
Directional command aliases for clearer intent:
// source -> target
commands.entity.;
commands.entity.;
// equivalent target-side wording
commands.entity.;
commands.entity.;
add vs set semantics
// insert-only: does not overwrite existing payload
commands.entity.;
commands.entity.;
// upsert: overwrites existing payload
commands.entity.;
Bevy-style construction on spawn/insert:
let alice = commands.spawn.id;
commands.spawn;
// multiple targets at once
commands.spawn;
Spawner helpers for creating related source entities
commands
.entity
.;
Detaching all incoming links to a target
commands
.entity
.;
Query relationships:
Query payload data from outgoing edges:
Deferred command behavior
EntityCommands are deferred in Bevy. Relationship mutations become visible after command application (flush in tests, schedule/apply deferred in app runtime).
When you need to know whether a mutation happened, validate via resulting world state or observers:
app.add_observer;
React to changes with observers:
app.add_observer;
License
MIT