Added an init_bundle method to World (#12573)

# Objective
Make it easy to get the ids of all the components in a bundle (and
initialise any components not yet initialised). This is fairly similar
to the `Bundle::get_component_ids()` method added in the observers PR
however that will return none for any non-initialised components. This
is exactly the API space covered by `Bundle::component_ids()` however
that isn't possible to call outside of `bevy_ecs` as it requires `&mut
Components` and `&mut Storages`.

## Solution
Added `World.init_bundle<B: Bundle>()` which similarly to
`init_component` and `init_resource`, initialises all components in the
bundle and returns a vector of their component ids.

---

## Changelog
Added the method `init_bundle` to `World` as a counterpart to
`init_component` and `init_resource`.

---------

Co-authored-by: James Liu <contact@jamessliu.com>
This commit is contained in:
TheBigCheese 2024-03-24 23:48:51 +00:00 committed by GitHub
parent 93b4c6c9a2
commit 86bd648570
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -18,7 +18,7 @@ pub use spawn_batch::*;
use crate::{
archetype::{ArchetypeComponentId, ArchetypeId, ArchetypeRow, Archetypes},
bundle::{Bundle, BundleInserter, BundleSpawner, Bundles},
bundle::{Bundle, BundleInfo, BundleInserter, BundleSpawner, Bundles},
change_detection::{MutUntyped, TicksMut},
component::{
Component, ComponentDescriptor, ComponentHooks, ComponentId, ComponentInfo, ComponentTicks,
@ -2085,6 +2085,20 @@ impl World {
self.storages.resources.clear();
self.storages.non_send_resources.clear();
}
/// Initializes all of the components in the given [`Bundle`] and returns both the component
/// ids and the bundle id.
///
/// This is largely equivalent to calling [`init_component`](Self::init_component) on each
/// component in the bundle.
#[inline]
pub fn init_bundle<B: Bundle>(&mut self) -> &BundleInfo {
let id = self
.bundles
.init_info::<B>(&mut self.components, &mut self.storages);
// SAFETY: We just initialised the bundle so its id should definitely be valid.
unsafe { self.bundles.get(id).debug_checked_unwrap() }
}
}
impl World {