From 06807ec3ea7df6e83eed51b38f9d5e3bea9e7045 Mon Sep 17 00:00:00 2001 From: mat Date: Mon, 6 Oct 2025 17:59:05 -0700 Subject: add try_query_entity --- azalea-client/src/entity_query.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) (limited to 'azalea-client/src/entity_query.rs') diff --git a/azalea-client/src/entity_query.rs b/azalea-client/src/entity_query.rs index 43e99c55..a1d761e3 100644 --- a/azalea-client/src/entity_query.rs +++ b/azalea-client/src/entity_query.rs @@ -6,7 +6,7 @@ use azalea_world::InstanceName; use bevy_ecs::{ component::Component, entity::Entity, - query::{QueryData, QueryFilter, QueryItem, ROQueryItem}, + query::{QueryData, QueryEntityError, QueryFilter, QueryItem, ROQueryItem}, world::World, }; use parking_lot::Mutex; @@ -47,21 +47,35 @@ impl Client { /// /// # Panics /// - /// This will panic if the component doesn't exist on the entity. + /// This will panic if the entity doesn't exist or if the query isn't valid + /// for the entity. For a non-panicking version, you may use + /// [`Self::try_query_entity`]. pub fn query_entity( &self, entity: Entity, f: impl FnOnce(QueryItem) -> R, ) -> R { - let mut ecs = self.ecs.lock(); - let mut qs = ecs.query::(); - let res = qs.get_mut(&mut ecs, entity).unwrap_or_else(|_| { + self.try_query_entity(entity, f).unwrap_or_else(|_| { panic!( "Entity is missing a required component {:?}", any::type_name::() ) - }); - f(res) + }) + } + + /// A convenience function for getting components from any entity, or None + /// if the query fails. + /// + /// If you're sure that the entity exists and that the query will succeed, + /// you can use [`Self::query_entity`]. + pub fn try_query_entity( + &self, + entity: Entity, + f: impl FnOnce(QueryItem) -> R, + ) -> Result { + let mut ecs = self.ecs.lock(); + let mut qs = ecs.query::(); + qs.get_mut(&mut ecs, entity).map(f) } /// Quickly returns a lightweight [`Entity`] for an arbitrary entity that -- cgit v1.2.3