bevy/crates/bevy_hierarchy/src
Rob Parrett 5b29402cc8
Add with_child to simplify spawning when there will only be one child (#14594)
# Objective

This idea came up in the context of a hypothetical "text sections as
entities" where text sections are children of a text bundle.

```rust
commands
    .spawn(TextBundle::default())
    .with_children(|parent} {
        parent.spawn(TextSection::from("Hello"));
    });
```

This is a bit cumbersome (but powerful and probably the way things are
headed). [`bsn!`](https://github.com/bevyengine/bevy/discussions/14437)
will eventually make this nicer, but in the mean time, this might
improve ergonomics for the common case where there is only one
`TextSection`.

## Solution

Add a `with_child` method to the `BuildChildren` trait that spawns a
single bundle and adds it as a child to the entity.

```rust
commands
    .spawn(TextBundle::default())
    .with_child(TextSection::from("Hello"));
```

## Testing

I added some tests, and modified the `button` example to use the new
method.

If any potential co-authors want to improve the tests, that would be
great.

## Alternatives

- Some sort of macro. See
https://github.com/tigregalis/bevy_spans_ent/blob/main/examples/macro.rs#L20.
I don't love this, personally, and it would probably be obsoleted by
`bsn!`.
- Wait for `bsn!`
- Add `with_children_batch` that takes an `Into<Iterator>` of bundles.
  ```rust
  with_children_batch(vec![TextSection::from("Hello")])
  ```
This is maybe not as useful as it sounds -- it only works with
homogeneous bundles, so no marker components or styles.
- If this doesn't seem valuable, doing nothing is cool with me.
2024-08-02 15:37:15 +00:00
..
components Minimal Bubbling Observers (#13991) 2024-07-15 13:39:41 +00:00
child_builder.rs Add with_child to simplify spawning when there will only be one child (#14594) 2024-08-02 15:37:15 +00:00
events.rs Require #[derive(Event)] on all Events (#7086) 2023-06-06 14:44:32 +00:00
hierarchy.rs Merge BuildWorldChildren and BuildChildren traits. (#14052) 2024-07-01 14:29:39 +00:00
lib.rs Merge BuildWorldChildren and BuildChildren traits. (#14052) 2024-07-01 14:29:39 +00:00
query_extension.rs Apply Clippy lints regarding lazy evaluation and closures (#14015) 2024-07-01 15:54:40 +00:00
valid_parent_check_plugin.rs Fixed #14248 and other URL issues (#14276) 2024-07-11 12:01:49 +00:00