Update .entry() docs to show both insert-then-modify and modify-or-insert examples (#19327)

# Objective

Fix https://github.com/bevyengine/bevy/issues/16379
This commit is contained in:
theotherphil 2025-05-26 21:27:20 +01:00 committed by GitHub
parent 8a223be651
commit 16a286dac3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1273,15 +1273,32 @@ impl<'a> EntityCommands<'a> {
/// #[derive(Component)] /// #[derive(Component)]
/// struct Level(u32); /// struct Level(u32);
/// ///
///
/// #[derive(Component, Default)]
/// struct Mana {
/// max: u32,
/// current: u32,
/// }
///
/// fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) { /// fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
/// // If a component already exists then modify it, otherwise insert a default value
/// commands /// commands
/// .entity(player.entity) /// .entity(player.entity)
/// .entry::<Level>() /// .entry::<Level>()
/// // Modify the component if it exists.
/// .and_modify(|mut lvl| lvl.0 += 1) /// .and_modify(|mut lvl| lvl.0 += 1)
/// // Otherwise, insert a default value.
/// .or_insert(Level(0)); /// .or_insert(Level(0));
///
/// // Add a default value if none exists, and then modify the existing or new value
/// commands
/// .entity(player.entity)
/// .entry::<Mana>()
/// .or_default()
/// .and_modify(|mut mana| {
/// mana.max += 10;
/// mana.current = mana.max;
/// });
/// } /// }
///
/// # bevy_ecs::system::assert_is_system(level_up_system); /// # bevy_ecs::system::assert_is_system(level_up_system);
/// ``` /// ```
pub fn entry<T: Component>(&mut self) -> EntityEntryCommands<T> { pub fn entry<T: Component>(&mut self) -> EntityEntryCommands<T> {