diff --git a/crates/bevy_core/src/lib.rs b/crates/bevy_core/src/lib.rs index a3b91ea2d9fc7..1b92d00d8911c 100644 --- a/crates/bevy_core/src/lib.rs +++ b/crates/bevy_core/src/lib.rs @@ -15,7 +15,7 @@ pub mod prelude { //! The Bevy Core Prelude. #[doc(hidden)] pub use crate::{ - FrameCountPlugin, Name, TaskPoolOptions, TaskPoolPlugin, TypeRegistrationPlugin, + DebugName, FrameCountPlugin, Name, TaskPoolOptions, TaskPoolPlugin, TypeRegistrationPlugin, }; } diff --git a/crates/bevy_core/src/name.rs b/crates/bevy_core/src/name.rs index f7fad0ca18e26..145c6e8060e93 100644 --- a/crates/bevy_core/src/name.rs +++ b/crates/bevy_core/src/name.rs @@ -1,4 +1,6 @@ -use bevy_ecs::{component::Component, reflect::ReflectComponent}; +use bevy_ecs::{ + component::Component, entity::Entity, query::WorldQuery, reflect::ReflectComponent, +}; use bevy_reflect::Reflect; use bevy_reflect::{std_traits::ReflectDefault, FromReflect}; use bevy_utils::AHasher; @@ -76,6 +78,40 @@ impl std::fmt::Display for Name { } } +/// Convenient query for giving a human friendly name to an entity. +/// +/// ```rust +/// # use bevy_core::prelude::*; +/// # use bevy_ecs::prelude::*; +/// # #[derive(Component)] pub struct Score(f32); +/// fn increment_score(mut scores: Query<(DebugName, &mut Score)>) { +/// for (name, mut score) in &mut scores { +/// score.0 += 1.0; +/// if score.0.is_nan() { +/// bevy_utils::tracing::error!("Score for {:?} is invalid", name); +/// } +/// } +/// } +/// # bevy_ecs::system::assert_is_system(increment_score); +/// ``` +#[derive(WorldQuery)] +pub struct DebugName { + /// A [`Name`] that the entity might have that is displayed if available. + pub name: Option<&'static Name>, + /// The unique identifier of the entity as a fallback. + pub entity: Entity, +} + +impl<'a> std::fmt::Debug for DebugNameItem<'a> { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self.name { + Some(name) => write!(f, "{:?} ({:?})", &name, &self.entity), + None => std::fmt::Debug::fmt(&self.entity, f), + } + } +} + /* Conversions from strings */ impl From<&str> for Name {