Skip to content

Commit 9167f02

Browse files
Create EntityCommands::remove_if (#18899)
# Objective Fixes #18857. ## Solution Add the requested method, and a `try_` variant as well. ## Testing It compiles, doctests succeed, and is trivial enough that I don't think it needs a unit test (correct me if I'm wrong though).
1 parent 2b7cecd commit 9167f02

File tree

1 file changed

+57
-0
lines changed
  • crates/bevy_ecs/src/system/commands

1 file changed

+57
-0
lines changed

crates/bevy_ecs/src/system/commands/mod.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1618,6 +1618,63 @@ impl<'a> EntityCommands<'a> {
16181618
self.queue_handled(entity_command::remove::<B>(), warn)
16191619
}
16201620

1621+
/// Removes a [`Bundle`] of components from the entity if the predicate returns true.
1622+
///
1623+
/// This is useful for chaining method calls.
1624+
///
1625+
/// # Example
1626+
///
1627+
/// ```
1628+
/// # use bevy_ecs::prelude::*;
1629+
/// # #[derive(Resource)]
1630+
/// # struct PlayerEntity { entity: Entity }
1631+
/// # impl PlayerEntity { fn is_spectator(&self) -> bool { true } }
1632+
/// #[derive(Component)]
1633+
/// struct Health(u32);
1634+
/// #[derive(Component)]
1635+
/// struct Strength(u32);
1636+
/// #[derive(Component)]
1637+
/// struct Defense(u32);
1638+
///
1639+
/// #[derive(Bundle)]
1640+
/// struct CombatBundle {
1641+
/// health: Health,
1642+
/// strength: Strength,
1643+
/// }
1644+
///
1645+
/// fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
1646+
/// commands
1647+
/// .entity(player.entity)
1648+
/// .remove_if::<(Defense, CombatBundle)>(|| !player.is_spectator());
1649+
/// }
1650+
/// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
1651+
/// ```
1652+
#[track_caller]
1653+
pub fn remove_if<B: Bundle>(&mut self, condition: impl FnOnce() -> bool) -> &mut Self {
1654+
if condition() {
1655+
self.remove::<B>()
1656+
} else {
1657+
self
1658+
}
1659+
}
1660+
1661+
/// Removes a [`Bundle`] of components from the entity if the predicate returns true.
1662+
///
1663+
/// This is useful for chaining method calls.
1664+
///
1665+
/// # Note
1666+
///
1667+
/// If the entity does not exist when this command is executed,
1668+
/// the resulting error will be ignored.
1669+
#[track_caller]
1670+
pub fn try_remove_if<B: Bundle>(&mut self, condition: impl FnOnce() -> bool) -> &mut Self {
1671+
if condition() {
1672+
self.try_remove::<B>()
1673+
} else {
1674+
self
1675+
}
1676+
}
1677+
16211678
/// Removes a [`Bundle`] of components from the entity.
16221679
///
16231680
/// This will remove all components that intersect with the provided bundle;

0 commit comments

Comments
 (0)