Convenience method for entity naming (#7186)
# Objective
- Trying to make it easier to have a more user friendly debugging name for when you want to print out an entity.
## Solution
- Add a new `WorldQuery` struct `DebugName` to format the `Name` if the entity has one, otherwise formats the `Entity` id.
This means we can do this and get more descriptive errors without much more effort:
```rust
fn my_system(moving: Query<(DebugName, &mut Position, &Velocity)>) {
for (name, mut position, velocity) in &mut moving {
position += velocity;
if position.is_nan() {
error!("{:?} has an invalid position state", name);
}
}
}
```
---
## Changelog
- Added `DebugName` world query for more human friendly debug names of entities.
This commit is contained in:
parent
ca2d91e7ab
commit
937fc039b1
@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -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;
|
||||
@ -77,6 +79,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 {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user