Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Immediate Execution of Commands on a &mut World #6186

Closed
wants to merge 13 commits into from
2 changes: 1 addition & 1 deletion crates/bevy_diagnostic/src/execute.rs
Expand Up @@ -24,7 +24,7 @@ impl Execute for &mut World {
///
/// let mut world = World::default();
/// let entity = world.execute(|_world, mut commands| {
/// commands.spawn().id()
/// commands.spawn(()).id()
Zeenobit marked this conversation as resolved.
Show resolved Hide resolved
/// });
///
/// assert!(world.get_entity(entity).is_some());
Expand Down
51 changes: 51 additions & 0 deletions tests/how_to_test_commands.rs
@@ -0,0 +1,51 @@
use bevy::{diagnostic::Execute, ecs::system::EntityCommands, prelude::*};

#[derive(Component, Default)]
struct Position(Vec2);

#[derive(Component)]
struct Destination(Vec2);

trait NavigateTo {
fn navigate_to(self, target: Entity);
}

impl NavigateTo for &mut EntityCommands<'_, '_, '_> {
/// Start navigation for this [`Entity`] towards [`Position`] of `target`.
fn navigate_to(self, target: Entity) {
let entity = self.id();
self.commands().add(move |world: &mut World| {
// Get position from target
let &Position(xy) = world
.get::<Position>(target)
.expect("target must have a position");
// Set navigation destination
world.entity_mut(entity).insert(Destination(xy));
});
}
}

/* ... */

#[test]
fn did_set_destination() {
const TARGET_POS: Vec2 = Vec2::new(5.0, 2.0);

let mut world = World::default();

// Spawn entity
let entity = world.spawn(Position::default()).id();

// Spawn target at `TARGET_POS`
let target = world.spawn(Position(TARGET_POS)).id();

world.execute(|_world, mut commands| {
commands.entity(entity).navigate_to(target);
});

// Ensure destination is set correctly to position of target
let &Destination(destination) = world
.get::<Destination>(entity)
.expect("entity must have a destination");
assert_eq!(destination, TARGET_POS);
}