Skip to content

Commit 4f1689e

Browse files
YohDeadfallcart
andcommitted
Added example of entity sorting by components (#1817)
We discussed with @alice-i-cecile privately on iterators and agreed that making a custom ordered iterator over query makes no sense since materialization is required anyway and it's better to reuse existing components or code. Therefore, just adding an example to the documentation as requested. Fixes #1470. Co-authored-by: Carter Anderson <[email protected]>
1 parent 07cf088 commit 4f1689e

File tree

1 file changed

+20
-0
lines changed
  • crates/bevy_ecs/src/world

1 file changed

+20
-0
lines changed

crates/bevy_ecs/src/world/mod.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,26 @@ impl World {
444444
/// assert_eq!(world.get::<Position>(entities[0]).unwrap(), &Position { x: 1.0, y: 0.0 });
445445
/// assert_eq!(world.get::<Position>(entities[1]).unwrap(), &Position { x: 0.0, y: 1.0 });
446446
/// ```
447+
///
448+
/// To iterate over entities in a deterministic order,
449+
/// sort the results of the query using the desired component as a key.
450+
/// Note that this requires fetching the whole result set from the query
451+
/// and allocation of a [Vec] to store it.
452+
///
453+
/// ```
454+
/// use bevy_ecs::{entity::Entity, world::World};
455+
/// let mut world = World::new();
456+
/// let a = world.spawn().insert_bundle((2, 4.0)).id();
457+
/// let b = world.spawn().insert_bundle((3, 5.0)).id();
458+
/// let c = world.spawn().insert_bundle((1, 6.0)).id();
459+
/// let mut entities = world.query::<(Entity, &i32, &f64)>()
460+
/// .iter(&world)
461+
/// .collect::<Vec<_>>();
462+
/// // Sort the query results by their `i32` component before comparing
463+
/// // to expected results. Query iteration order should not be relied on.
464+
/// entities.sort_by_key(|e| e.1);
465+
/// assert_eq!(entities, vec![(c, &1, &6.0), (a, &2, &4.0), (b, &3, &5.0)]);
466+
/// ```
447467
#[inline]
448468
pub fn query<Q: WorldQuery>(&mut self) -> QueryState<Q, ()> {
449469
QueryState::new(self)

0 commit comments

Comments
 (0)