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

[Merged by Bors] - Add get_entity to Commands #5854

Closed
wants to merge 8 commits into from
43 changes: 36 additions & 7 deletions crates/bevy_ecs/src/system/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,17 +243,46 @@ impl<'w, 's> Commands<'w, 's> {
/// }
/// # bevy_ecs::system::assert_is_system(example_system);
/// ```
#[inline]
#[track_caller]
pub fn entity<'a>(&'a mut self, entity: Entity) -> EntityCommands<'w, 's, 'a> {
assert!(
self.entities.contains(entity),
"Attempting to create an EntityCommands for entity {:?}, which doesn't exist.",
entity
);
EntityCommands {
self.get_entity(entity).unwrap_or_else(|| {
panic!(
"Attempting to create an EntityCommands for entity {:?}, which doesn't exist.",
entity
)
})
}

/// Returns an option containing an [`EntityCommands`] builder for the requested [`Entity`] if it exists, otherwise None.
cart marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Example
///
/// ```
/// use bevy_ecs::prelude::*;
///
/// #[derive(Component)]
/// struct Label(&'static str);

/// fn example_system(mut commands: Commands) {
/// // Create a new, empty entity
/// let entity = commands.spawn().id();
///
/// // Get the entity if it still exists, which it will in this case
/// if let Some(mut entity_commands) = commands.get_entity(entity) {
/// // adds a single component to the entity
/// entity_commands.insert(Label("hello world"));
/// }
/// }
/// # bevy_ecs::system::assert_is_system(example_system);
/// ```
#[inline]
#[track_caller]
pub fn get_entity<'a>(&'a mut self, entity: Entity) -> Option<EntityCommands<'w, 's, 'a>> {
james-j-obrien marked this conversation as resolved.
Show resolved Hide resolved
self.entities.contains(entity).then_some(EntityCommands {
entity,
commands: self,
}
})
}

/// Spawns entities to the [`World`] according to the given iterator (or a type that can
Expand Down