From f4776f2ec413bb80ff4ee51e04bb57f0a44d9983 Mon Sep 17 00:00:00 2001 From: Jerome Humbert Date: Sun, 10 Oct 2021 23:04:05 +0000 Subject: [PATCH] Add entity ID to expect() message (#2943) Add the entity ID and generation to the expect() message of two world accessors, to make it easier to debug use-after-free issues. Coupled with e.g. bevy-inspector-egui which also displays the entity ID, this makes it much easier to identify what entity is being misused. # Objective Make it easier to identity an entity being accessed after being deleted. ## Solution Augment the error message of some `expect()` call with the entity ID and generation. Combined with some external tool like `bevy-inspector-egui`, which also displays the entity ID, this increases the chances to be able to identify the entity, and therefore find the error that led to a use-after-despawn. --- crates/bevy_ecs/src/world/mod.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index 0e61a5bdc22ed..e9f56a58a8ec9 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -197,7 +197,9 @@ impl World { /// ``` #[inline] pub fn entity(&self, entity: Entity) -> EntityRef { - self.get_entity(entity).expect("Entity does not exist") + // Lazily evaluate panic!() via unwrap_or_else() to avoid allocation unless failure + self.get_entity(entity) + .unwrap_or_else(|| panic!("Entity {:?} does not exist", entity)) } /// Retrieves an [EntityMut] that exposes read and write operations for the given `entity`. @@ -223,7 +225,9 @@ impl World { /// ``` #[inline] pub fn entity_mut(&mut self, entity: Entity) -> EntityMut { - self.get_entity_mut(entity).expect("Entity does not exist") + // Lazily evaluate panic!() via unwrap_or_else() to avoid allocation unless failure + self.get_entity_mut(entity) + .unwrap_or_else(|| panic!("Entity {:?} does not exist", entity)) } /// Returns an [EntityMut] for the given `entity` (if it exists) or spawns one if it doesn't exist.