Make the ObservedBy component useful to public consumers (#19591)

# Objective

As raised by @Jondolf, this type is `pub`, and useful for various
consumers to ensure cleanup or debugging.

However, it doesn't offer any way to actually view the data.

## Solution

- Add a read-only view of the data.
- Don't add any (easy) way to mutate the data, as this presents a huge
footgun.
- Implement Reflect and register the component so you can see it in
inspectors nicely.
This commit is contained in:
Alice Cecile 2025-06-12 13:07:11 -07:00 committed by GitHub
parent 1dfe83bb8d
commit 58c276ab44
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 1 deletions

View File

@ -106,10 +106,13 @@ impl Default for App {
#[cfg(feature = "bevy_reflect")]
{
use bevy_ecs::observer::ObservedBy;
app.init_resource::<AppTypeRegistry>();
app.register_type::<Name>();
app.register_type::<ChildOf>();
app.register_type::<Children>();
app.register_type::<ObservedBy>();
}
#[cfg(feature = "reflect_functions")]

View File

@ -6,12 +6,24 @@ use crate::{
};
use alloc::vec::Vec;
#[cfg(feature = "bevy_reflect")]
use crate::prelude::ReflectComponent;
use super::Observer;
/// Tracks a list of entity observers for the [`Entity`] [`ObservedBy`] is added to.
#[derive(Default)]
#[derive(Default, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(Component, Debug))]
pub struct ObservedBy(pub(crate) Vec<Entity>);
impl ObservedBy {
/// Provides a read-only reference to the list of entities observing this entity.
pub fn get(&self) -> &[Entity] {
&self.0
}
}
impl Component for ObservedBy {
const STORAGE_TYPE: StorageType = StorageType::SparseSet;
type Mutability = Mutable;