Struct DeferredWorld
pub struct DeferredWorld<'w> { /* private fields */ }Expand description
A World reference that disallows structural ECS changes.
This includes initializing resources, registering components or spawning entities.
This means that in order to add entities, for example, you will need to use commands instead of the world directly.
Implementations§
§impl<'w> DeferredWorld<'w>
impl<'w> DeferredWorld<'w>
pub fn reborrow(&mut self) -> DeferredWorld<'_>
pub fn reborrow(&mut self) -> DeferredWorld<'_>
Reborrow self as a new instance of DeferredWorld
pub fn commands(&mut self) -> Commands<'_, '_>
pub fn commands(&mut self) -> Commands<'_, '_>
Creates a Commands instance that pushes to the world’s command queue
pub fn get_entity_mut<F>(
&mut self,
entities: F,
) -> Result<<F as WorldEntityFetch>::DeferredMut<'_>, EntityMutableFetchError>where
F: WorldEntityFetch,
pub fn get_entity_mut<F>(
&mut self,
entities: F,
) -> Result<<F as WorldEntityFetch>::DeferredMut<'_>, EntityMutableFetchError>where
F: WorldEntityFetch,
Returns EntityMuts that expose read and write operations for the
given entities, returning Err if any of the given entities do not
exist. Instead of immediately unwrapping the value returned from this
function, prefer World::entity_mut.
This function supports fetching a single entity or multiple entities:
- Pass an
Entityto receive a singleEntityMut. - Pass a slice of
Entitys to receive aVec<EntityMut>. - Pass an array of
Entitys to receive an equally-sized array ofEntityMuts. - Pass an
&EntityHashSetto receive anEntityHashMap<EntityMut>.
As DeferredWorld does not allow structural changes, all returned
references are EntityMuts, which do not allow structural changes
(i.e. adding/removing components or despawning the entity).
§Errors
- Returns
EntityMutableFetchError::NotSpawnedif any of the givenentitiesdo not exist in the world.- Only the first entity found to be missing will be returned.
- Returns
EntityMutableFetchError::AliasedMutabilityif the same entity is requested multiple times.
§Examples
For examples, see DeferredWorld::entity_mut.
pub fn entity_mut<F>(
&mut self,
entities: F,
) -> <F as WorldEntityFetch>::DeferredMut<'_>where
F: WorldEntityFetch,
pub fn entity_mut<F>(
&mut self,
entities: F,
) -> <F as WorldEntityFetch>::DeferredMut<'_>where
F: WorldEntityFetch,
Returns EntityMuts that expose read and write operations for the
given entities. This will panic if any of the given entities do not
exist. Use DeferredWorld::get_entity_mut if you want to check for
entity existence instead of implicitly panicking.
This function supports fetching a single entity or multiple entities:
- Pass an
Entityto receive a singleEntityMut. - Pass a slice of
Entitys to receive aVec<EntityMut>. - Pass an array of
Entitys to receive an equally-sized array ofEntityMuts. - Pass an
&EntityHashSetto receive anEntityHashMap<EntityMut>.
As DeferredWorld does not allow structural changes, all returned
references are EntityMuts, which do not allow structural changes
(i.e. adding/removing components or despawning the entity).
§Panics
If any of the given entities do not exist in the world.
§Examples
§Single Entity
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world: DeferredWorld = // ...
let mut entity_mut = world.entity_mut(entity);
let mut position = entity_mut.get_mut::<Position>().unwrap();
position.y = 1.0;
assert_eq!(position.x, 0.0);§Array of Entitys
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world: DeferredWorld = // ...
let [mut e1_ref, mut e2_ref] = world.entity_mut([e1, e2]);
let mut e1_position = e1_ref.get_mut::<Position>().unwrap();
e1_position.x = 1.0;
assert_eq!(e1_position.x, 1.0);
let mut e2_position = e2_ref.get_mut::<Position>().unwrap();
e2_position.x = 2.0;
assert_eq!(e2_position.x, 2.0);§Slice of Entitys
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world: DeferredWorld = // ...
let ids = vec![e1, e2, e3];
for mut eref in world.entity_mut(&ids[..]) {
let mut pos = eref.get_mut::<Position>().unwrap();
pos.y = 2.0;
assert_eq!(pos.y, 2.0);
}§&EntityHashSet
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world: DeferredWorld = // ...
let ids = EntityHashSet::from_iter([e1, e2, e3]);
for (_id, mut eref) in world.entity_mut(&ids) {
let mut pos = eref.get_mut::<Position>().unwrap();
pos.y = 2.0;
assert_eq!(pos.y, 2.0);
}pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>)
pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>)
Simultaneously provides access to entity data and a command queue, which
will be applied when the World is next flushed.
This allows using borrowed entity data to construct commands where the borrow checker would otherwise prevent it.
See World::entities_and_commands for the non-deferred version.
§Example
#[derive(Component)]
struct Targets(Vec<Entity>);
#[derive(Component)]
struct TargetedBy(Entity);
let mut world: DeferredWorld = // ...
let (entities, mut commands) = world.entities_and_commands();
let entity = entities.get(eid).unwrap();
for &target in entity.get::<Targets>().unwrap().0.iter() {
commands.entity(target).insert(TargetedBy(eid));
}pub fn query<'s, D, F>(
&mut self,
state: &'s mut QueryState<D, F>,
) -> Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
pub fn query<'s, D, F>(
&mut self,
state: &'s mut QueryState<D, F>,
) -> Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
Returns Query for the given QueryState, which is used to efficiently
run queries on the World by storing and reusing the QueryState.
§Panics
If state is from a different world then self
pub fn resource_mut<R>(&mut self) -> Mut<'_, R>
pub fn resource_mut<R>(&mut self) -> Mut<'_, R>
Gets a mutable reference to the resource of the given type
§Panics
Panics if the resource does not exist.
Use get_resource_mut instead if you want to handle this case.
pub fn get_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>
pub fn get_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>
Gets a mutable reference to the resource of the given type if it exists
pub fn non_send_resource_mut<R>(&mut self) -> Mut<'_, R>where
R: 'static,
👎Deprecated since 0.19.0: use DeferredWorld::non_send_mut
pub fn non_send_resource_mut<R>(&mut self) -> Mut<'_, R>where
R: 'static,
use DeferredWorld::non_send_mut
Gets a mutable reference to a non-send resource of the given type, if it exists.
pub fn non_send_mut<R>(&mut self) -> Mut<'_, R>where
R: 'static,
pub fn non_send_mut<R>(&mut self) -> Mut<'_, R>where
R: 'static,
Gets a mutable reference to the non-send data of the given type, if it exists.
§Panics
Panics if the data does not exist.
Use get_non_send_mut instead if you want to handle this case.
This function will panic if it isn’t called from the same thread that the data was inserted from.
pub fn get_non_send_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>where
R: 'static,
👎Deprecated since 0.19.0: use DeferredWorld::get_non_send_mut
pub fn get_non_send_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>where
R: 'static,
use DeferredWorld::get_non_send_mut
Gets a mutable reference to a non-send resource of the given type, if it exists.
Otherwise returns None.
pub fn get_non_send_mut<R>(&mut self) -> Option<Mut<'_, R>>where
R: 'static,
pub fn get_non_send_mut<R>(&mut self) -> Option<Mut<'_, R>>where
R: 'static,
Gets a mutable reference to non-send data of the given type, if it exists.
Otherwise returns None.
§Panics
This function will panic if it isn’t called from the same thread that the data was inserted from.
pub fn write_message<M>(&mut self, message: M) -> Option<MessageId<M>>where
M: Message,
pub fn write_message<M>(&mut self, message: M) -> Option<MessageId<M>>where
M: Message,
pub fn write_message_default<E>(&mut self) -> Option<MessageId<E>>
pub fn write_message_default<E>(&mut self) -> Option<MessageId<E>>
pub fn write_message_batch<E>(
&mut self,
events: impl IntoIterator<Item = E>,
) -> Option<WriteBatchIds<E>>where
E: Message,
pub fn write_message_batch<E>(
&mut self,
events: impl IntoIterator<Item = E>,
) -> Option<WriteBatchIds<E>>where
E: Message,
pub fn get_resource_mut_by_id(
&mut self,
component_id: ComponentId,
) -> Option<MutUntyped<'_>>
pub fn get_resource_mut_by_id( &mut self, component_id: ComponentId, ) -> Option<MutUntyped<'_>>
Gets a pointer to the resource with the id ComponentId if it exists.
The returned pointer may be used to modify the resource, as long as the mutable borrow
of the World is still valid.
You should prefer to use the typed API World::get_resource_mut where possible and only
use this in cases where the actual types are not known at compile time.
pub fn get_non_send_mut_by_id(
&mut self,
component_id: ComponentId,
) -> Option<MutUntyped<'_>>
pub fn get_non_send_mut_by_id( &mut self, component_id: ComponentId, ) -> Option<MutUntyped<'_>>
Gets mutable access to !Send data with the id ComponentId if it exists.
The returned pointer may be used to modify the data, as long as the mutable borrow
of the World is still valid.
You should prefer to use the typed API DeferredWorld::get_non_send_mut where possible
and only use this in cases where the actual types are not known at compile time.
§Panics
This function will panic if it isn’t called from the same thread that the data was inserted from.
pub fn get_mut_by_id(
&mut self,
entity: Entity,
component_id: ComponentId,
) -> Option<MutUntyped<'_>>
pub fn get_mut_by_id( &mut self, entity: Entity, component_id: ComponentId, ) -> Option<MutUntyped<'_>>
Retrieves a mutable untyped reference to the given entity’s Component of the given ComponentId.
Returns None if the entity does not have a Component of the given type.
You should prefer to use the typed API World::get_mut where possible and only
use this in cases where the actual types are not known at compile time.
pub unsafe fn trigger_raw<'a, E>(
&mut self,
event_key: EventKey,
event: &mut E,
trigger: &mut <E as Event>::Trigger<'a>,
caller: MaybeLocation,
)where
E: Event,
pub unsafe fn trigger_raw<'a, E>(
&mut self,
event_key: EventKey,
event: &mut E,
trigger: &mut <E as Event>::Trigger<'a>,
caller: MaybeLocation,
)where
E: Event,
Triggers all event observers for the given targets
§Safety
- Caller must ensure
Eis accessible as the type represented byevent_key
pub fn trigger<'a>(&mut self, event: impl Event : Default>)
pub fn trigger<'a>(&mut self, event: impl Event : Default>)
pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_>
pub fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_>
Gets an UnsafeWorldCell containing the underlying world.
§Safety
- must only be used to make non-structural ECS changes
pub fn change_tick(&mut self) -> Tick
pub fn change_tick(&mut self) -> Tick
Gets the current change tick of DeferredWorld.
Methods from Deref<Target = World>§
pub fn event_key<E>(&self) -> Option<EventKey>where
E: Event,
pub fn event_key<E>(&self) -> Option<EventKey>where
E: Event,
Fetches the EventKey for this event type,
if it has already been generated.
This is used by various dynamically typed observer APIs,
such as DeferredWorld::trigger_raw.
pub fn get_reflect(
&self,
entity: Entity,
type_id: TypeId,
) -> Result<&(dyn Reflect + 'static), GetComponentReflectError>
pub fn get_reflect( &self, entity: Entity, type_id: TypeId, ) -> Result<&(dyn Reflect + 'static), GetComponentReflectError>
Retrieves a reference to the given entity’s Component of the given type_id using
reflection.
Requires implementing Reflect for the Component (e.g., using #[derive(Reflect))
and app.register_type::<TheComponent>() to have been called1.
If you want to call this with a ComponentId, see World::components and Components::get_id to get
the corresponding TypeId.
Also see the crate documentation for [bevy_reflect] for more information on
Reflect and bevy’s reflection capabilities.
§Errors
See GetComponentReflectError for the possible errors and their descriptions.
§Example
use bevy_ecs::prelude::*;
use bevy_reflect::Reflect;
use std::any::TypeId;
// define a `Component` and derive `Reflect` for it
#[derive(Component, Reflect)]
struct MyComponent;
// create a `World` for this example
let mut world = World::new();
// Note: This is usually handled by `App::register_type()`, but this example cannot use `App`.
world.init_resource::<AppTypeRegistry>();
world.get_resource_mut::<AppTypeRegistry>().unwrap().write().register::<MyComponent>();
// spawn an entity with a `MyComponent`
let entity = world.spawn(MyComponent).id();
// retrieve a reflected reference to the entity's `MyComponent`
let comp_reflected: &dyn Reflect = world.get_reflect(entity, TypeId::of::<MyComponent>()).unwrap();
// make sure we got the expected type
assert!(comp_reflected.is::<MyComponent>());§Note
Requires the bevy_reflect feature (included in the default features).
More specifically: Requires
TypeDataforReflectFromPtrto be registered for the giventype_id, which is automatically handled when derivingReflectand callingApp::register_type. ↩
pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_>
pub fn as_unsafe_world_cell_readonly(&self) -> UnsafeWorldCell<'_>
Creates a new UnsafeWorldCell view with only read access to everything.
pub fn entity_allocator(&self) -> &EntityAllocator
pub fn entity_allocator(&self) -> &EntityAllocator
Retrieves this world’s EntityAllocator collection.
pub fn entity_count(&self) -> u32
pub fn entity_count(&self) -> u32
Retrieves the number of Entities in the world.
This is helpful as a diagnostic, but it can also be used effectively in tests.
pub fn archetypes(&self) -> &Archetypes
pub fn archetypes(&self) -> &Archetypes
Retrieves this world’s Archetypes collection.
pub fn components(&self) -> &Components
pub fn components(&self) -> &Components
Retrieves this world’s Components collection.
pub fn resource_entities(&self) -> &ResourceEntities
pub fn resource_entities(&self) -> &ResourceEntities
Retrieves this world’s ResourceEntities.
pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_>
pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_>
Prepares a ComponentsQueuedRegistrator for the world.
NOTE: ComponentsQueuedRegistrator is easily misused.
See its docs for important notes on when and how it should be used.
pub fn removed_components(&self) -> &RemovedComponentMessages
pub fn removed_components(&self) -> &RemovedComponentMessages
Retrieves this world’s RemovedComponentMessages collection
pub fn get_required_components<C>(&self) -> Option<&RequiredComponents>where
C: Component,
pub fn get_required_components<C>(&self) -> Option<&RequiredComponents>where
C: Component,
Retrieves the required components for the given component type, if it exists.
pub fn get_required_components_by_id(
&self,
id: ComponentId,
) -> Option<&RequiredComponents>
pub fn get_required_components_by_id( &self, id: ComponentId, ) -> Option<&RequiredComponents>
Retrieves the required components for the component of the given ComponentId, if it exists.
pub fn component_id<T>(&self) -> Option<ComponentId>where
T: Component,
pub fn component_id<T>(&self) -> Option<ComponentId>where
T: Component,
Returns the ComponentId of the given Component type T.
The returned ComponentId is specific to the World instance
it was retrieved from and should not be used with another World instance.
Returns None if the Component type has not yet been initialized within
the World using World::register_component.
use bevy_ecs::prelude::*;
let mut world = World::new();
#[derive(Component)]
struct ComponentA;
let component_a_id = world.register_component::<ComponentA>();
assert_eq!(component_a_id, world.component_id::<ComponentA>().unwrap())§See also
pub fn resource_id<T>(&self) -> Option<ComponentId>where
T: Resource,
👎Deprecated since 0.19.0: use component_id
pub fn resource_id<T>(&self) -> Option<ComponentId>where
T: Resource,
use component_id
Returns the ComponentId of the given Resource type T.
The returned ComponentId is specific to the World instance it was retrieved from
and should not be used with another World instance.
Returns None if the Resource type has not yet been initialized within the
World using World::register_resource, World::init_resource or World::insert_resource.
pub fn entity<F>(&self, entities: F) -> <F as WorldEntityFetch>::Ref<'_>where
F: WorldEntityFetch,
pub fn entity<F>(&self, entities: F) -> <F as WorldEntityFetch>::Ref<'_>where
F: WorldEntityFetch,
Returns EntityRefs that expose read-only operations for the given
entities. This will panic if any of the given entities do not exist. Use
World::get_entity if you want to check for entity existence instead
of implicitly panicking.
This function supports fetching a single entity or multiple entities:
- Pass an
Entityto receive a singleEntityRef. - Pass a slice of
Entitys to receive aVec<EntityRef>. - Pass an array of
Entitys to receive an equally-sized array ofEntityRefs.
§Panics
If any of the given entities do not exist in the world.
§Examples
§Single Entity
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world = World::new();
let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
let position = world.entity(entity).get::<Position>().unwrap();
assert_eq!(position.x, 0.0);§Array of Entitys
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world = World::new();
let e1 = world.spawn(Position { x: 0.0, y: 0.0 }).id();
let e2 = world.spawn(Position { x: 1.0, y: 1.0 }).id();
let [e1_ref, e2_ref] = world.entity([e1, e2]);
let e1_position = e1_ref.get::<Position>().unwrap();
assert_eq!(e1_position.x, 0.0);
let e2_position = e2_ref.get::<Position>().unwrap();
assert_eq!(e2_position.x, 1.0);§Slice of Entitys
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world = World::new();
let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let ids = vec![e1, e2, e3];
for eref in world.entity(&ids[..]) {
assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
}§EntityHashSet
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world = World::new();
let e1 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e2 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let e3 = world.spawn(Position { x: 0.0, y: 1.0 }).id();
let ids = EntityHashSet::from_iter([e1, e2, e3]);
for (_id, eref) in world.entity(&ids) {
assert_eq!(eref.get::<Position>().unwrap().y, 1.0);
}pub fn inspect_entity(
&self,
entity: Entity,
) -> Result<impl Iterator<Item = &ComponentInfo>, EntityNotSpawnedError>
pub fn inspect_entity( &self, entity: Entity, ) -> Result<impl Iterator<Item = &ComponentInfo>, EntityNotSpawnedError>
Returns the components of an Entity through ComponentInfo.
pub fn get_entity<F>(
&self,
entities: F,
) -> Result<<F as WorldEntityFetch>::Ref<'_>, EntityNotSpawnedError>where
F: WorldEntityFetch,
pub fn get_entity<F>(
&self,
entities: F,
) -> Result<<F as WorldEntityFetch>::Ref<'_>, EntityNotSpawnedError>where
F: WorldEntityFetch,
Returns EntityRefs that expose read-only operations for the given
entities, returning Err if any of the given entities do not exist.
Instead of immediately unwrapping the value returned from this function,
prefer World::entity.
This function supports fetching a single entity or multiple entities:
- Pass an
Entityto receive a singleEntityRef. - Pass a slice of
Entitys to receive aVec<EntityRef>. - Pass an array of
Entitys to receive an equally-sized array ofEntityRefs. - Pass a reference to a
EntityHashSetto receive anEntityHashMap<EntityRef>.
§Errors
If any of the given entities do not exist in the world, the first
Entity found to be missing will return an EntityNotSpawnedError.
§Examples
For examples, see World::entity.
pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>>
pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>>
Returns an Entity iterator of current entities.
This is useful in contexts where you only have immutable access to the World.
If you have mutable access to the World, use
query()::<EntityRef>().iter(&world) instead.
Note that this does iterate through all entities, including resource entities.
pub fn get<T>(&self, entity: Entity) -> Option<&T>where
T: Component,
pub fn get<T>(&self, entity: Entity) -> Option<&T>where
T: Component,
Retrieves a reference to the given entity’s Component of the given type.
Returns None if the entity does not have a Component of the given type.
use bevy_ecs::{component::Component, world::World};
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
let mut world = World::new();
let entity = world.spawn(Position { x: 0.0, y: 0.0 }).id();
let position = world.get::<Position>(entity).unwrap();
assert_eq!(position.x, 0.0);pub fn try_query<D>(&self) -> Option<QueryState<D>>where
D: QueryData,
pub fn try_query<D>(&self) -> Option<QueryState<D>>where
D: QueryData,
Returns QueryState for the given QueryData, which is used to efficiently
run queries on the World by storing and reusing the QueryState.
use bevy_ecs::{component::Component, entity::Entity, world::World};
#[derive(Component, Debug, PartialEq)]
struct Position {
x: f32,
y: f32,
}
let mut world = World::new();
world.spawn_batch(vec![
Position { x: 0.0, y: 0.0 },
Position { x: 1.0, y: 1.0 },
]);
fn get_positions(world: &World) -> Vec<(Entity, &Position)> {
let mut query = world.try_query::<(Entity, &Position)>().unwrap();
query.iter(world).collect()
}
let positions = get_positions(&world);
assert_eq!(world.get::<Position>(positions[0].0).unwrap(), positions[0].1);
assert_eq!(world.get::<Position>(positions[1].0).unwrap(), positions[1].1);Requires only an immutable world reference, but may fail if, for example, the components that make up this query have not been registered into the world.
use bevy_ecs::{component::Component, entity::Entity, world::World};
#[derive(Component)]
struct A;
let mut world = World::new();
let none_query = world.try_query::<&A>();
assert!(none_query.is_none());
world.register_component::<A>();
let some_query = world.try_query::<&A>();
assert!(some_query.is_some());pub fn try_query_filtered<D, F>(&self) -> Option<QueryState<D, F>>where
D: QueryData,
F: QueryFilter,
pub fn try_query_filtered<D, F>(&self) -> Option<QueryState<D, F>>where
D: QueryData,
F: QueryFilter,
Returns QueryState for the given filtered QueryData, which is used to efficiently
run queries on the World by storing and reusing the QueryState.
use bevy_ecs::{component::Component, entity::Entity, world::World, query::With};
#[derive(Component)]
struct A;
#[derive(Component)]
struct B;
let mut world = World::new();
let e1 = world.spawn(A).id();
let e2 = world.spawn((A, B)).id();
let mut query = world.try_query_filtered::<Entity, With<B>>().unwrap();
let matching_entities = query.iter(&world).collect::<Vec<Entity>>();
assert_eq!(matching_entities, vec![e2]);Requires only an immutable world reference, but may fail if, for example, the components that make up this query have not been registered into the world.
pub fn removed<T>(&self) -> impl Iterator<Item = Entity>where
T: Component,
pub fn removed<T>(&self) -> impl Iterator<Item = Entity>where
T: Component,
Returns an iterator of entities that had components of type T removed
since the last call to World::clear_trackers.
pub fn removed_with_id(
&self,
component_id: ComponentId,
) -> impl Iterator<Item = Entity>
pub fn removed_with_id( &self, component_id: ComponentId, ) -> impl Iterator<Item = Entity>
Returns an iterator of entities that had components with the given component_id removed
since the last call to World::clear_trackers.
pub fn contains_resource<R>(&self) -> boolwhere
R: Resource,
pub fn contains_resource<R>(&self) -> boolwhere
R: Resource,
Returns true if a resource of type R exists. Otherwise returns false.
pub fn contains_resource_by_id(&self, component_id: ComponentId) -> bool
pub fn contains_resource_by_id(&self, component_id: ComponentId) -> bool
Returns true if a resource with provided component_id exists. Otherwise returns false.
pub fn contains_non_send<R>(&self) -> boolwhere
R: 'static,
pub fn contains_non_send<R>(&self) -> boolwhere
R: 'static,
Returns true if !Send data of type R exists. Otherwise returns false.
pub fn contains_non_send_by_id(&self, component_id: ComponentId) -> bool
pub fn contains_non_send_by_id(&self, component_id: ComponentId) -> bool
Returns true if !Send data with component_id exists. Otherwise returns false.
pub fn is_resource_added<R>(&self) -> boolwhere
R: Resource,
pub fn is_resource_added<R>(&self) -> boolwhere
R: Resource,
Returns true if a resource of type R exists and was added since the world’s
last_change_tick. Otherwise, this returns false.
This means that:
- When called from an exclusive system, this will check for additions since the system last ran.
- When called elsewhere, this will check for additions since the last time that
World::clear_trackerswas called.
pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool
pub fn is_resource_added_by_id(&self, component_id: ComponentId) -> bool
Returns true if a resource with id component_id exists and was added since the world’s
last_change_tick. Otherwise, this returns false.
This means that:
- When called from an exclusive system, this will check for additions since the system last ran.
- When called elsewhere, this will check for additions since the last time that
World::clear_trackerswas called.
pub fn is_resource_changed<R>(&self) -> boolwhere
R: Resource,
pub fn is_resource_changed<R>(&self) -> boolwhere
R: Resource,
Returns true if a resource of type R exists and was modified since the world’s
last_change_tick. Otherwise, this returns false.
This means that:
- When called from an exclusive system, this will check for changes since the system last ran.
- When called elsewhere, this will check for changes since the last time that
World::clear_trackerswas called.
pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool
pub fn is_resource_changed_by_id(&self, component_id: ComponentId) -> bool
Returns true if a resource with id component_id exists and was modified since the world’s
last_change_tick. Otherwise, this returns false.
This means that:
- When called from an exclusive system, this will check for changes since the system last ran.
- When called elsewhere, this will check for changes since the last time that
World::clear_trackerswas called.
pub fn get_resource_change_ticks<R>(&self) -> Option<ComponentTicks>where
R: Resource,
pub fn get_resource_change_ticks<R>(&self) -> Option<ComponentTicks>where
R: Resource,
Retrieves the change ticks for the given resource.
pub fn get_resource_change_ticks_by_id(
&self,
component_id: ComponentId,
) -> Option<ComponentTicks>
pub fn get_resource_change_ticks_by_id( &self, component_id: ComponentId, ) -> Option<ComponentTicks>
Retrieves the change ticks for the given ComponentId.
You should prefer to use the typed API World::get_resource_change_ticks where possible.
pub fn resource<R>(&self) -> &Rwhere
R: Resource,
pub fn resource<R>(&self) -> &Rwhere
R: Resource,
Gets a reference to the resource of the given type
§Panics
Panics if the resource does not exist.
Use get_resource instead if you want to handle this case.
If you want to instead insert a value if the resource does not exist,
use get_resource_or_insert_with.
pub fn resource_ref<R>(&self) -> Ref<'_, R>where
R: Resource,
pub fn resource_ref<R>(&self) -> Ref<'_, R>where
R: Resource,
Gets a reference to the resource of the given type
§Panics
Panics if the resource does not exist.
Use get_resource_ref instead if you want to handle this case.
If you want to instead insert a value if the resource does not exist,
use get_resource_or_insert_with.
pub fn get_resource<R>(&self) -> Option<&R>where
R: Resource,
pub fn get_resource<R>(&self) -> Option<&R>where
R: Resource,
Gets a reference to the resource of the given type if it exists
pub fn get_resource_ref<R>(&self) -> Option<Ref<'_, R>>where
R: Resource,
pub fn get_resource_ref<R>(&self) -> Option<Ref<'_, R>>where
R: Resource,
Gets a reference including change detection to the resource of the given type if it exists.
pub fn non_send_resource<R>(&self) -> &Rwhere
R: 'static,
👎Deprecated since 0.19.0: use World::non_send
pub fn non_send_resource<R>(&self) -> &Rwhere
R: 'static,
use World::non_send
Gets an immutable reference to a non-send resource of the given type, if it exists.
pub fn non_send<R>(&self) -> &Rwhere
R: 'static,
pub fn non_send<R>(&self) -> &Rwhere
R: 'static,
Gets an immutable reference to the non-send data of the given type, if it exists.
§Panics
Panics if the data does not exist.
Use get_non_send instead if you want to handle this case.
This function will panic if it isn’t called from the same thread that the resource was inserted from.
pub fn get_non_send_resource<R>(&self) -> Option<&R>where
R: 'static,
👎Deprecated since 0.19.0: use World::get_non_send
pub fn get_non_send_resource<R>(&self) -> Option<&R>where
R: 'static,
use World::get_non_send
Gets a reference to a non-send resource of the given type, if it exists.
Otherwise returns None.
pub fn get_non_send<R>(&self) -> Option<&R>where
R: 'static,
pub fn get_non_send<R>(&self) -> Option<&R>where
R: 'static,
Gets a reference to the non-send data of the given type, if it exists.
Otherwise returns None.
§Panics
This function will panic if it isn’t called from the same thread that the resource was inserted from.
pub fn read_change_tick(&self) -> Tick
pub fn read_change_tick(&self) -> Tick
Reads the current change tick of this world.
If you have exclusive (&mut) access to the world, consider using change_tick(),
which is more efficient since it does not require atomic synchronization.
pub fn last_change_tick(&self) -> Tick
pub fn last_change_tick(&self) -> Tick
When called from within an exclusive system (a System that takes &mut World as its first
parameter), this method returns the Tick indicating the last time the exclusive system was run.
Otherwise, this returns the Tick indicating the last time that World::clear_trackers was called.
pub fn fallback_error_handler(&self) -> fn(BevyError, ErrorContext)
pub fn fallback_error_handler(&self) -> fn(BevyError, ErrorContext)
Convenience method for accessing the world’s fallback error handler,
which can be overwritten with FallbackErrorHandler.
pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>>
pub fn get_resource_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>>
Gets a pointer to the resource with the id ComponentId if it exists.
The returned pointer must not be used to modify the resource, and must not be
dereferenced after the immutable borrow of the World ends.
You should prefer to use the typed API World::get_resource where possible and only
use this in cases where the actual types are not known at compile time.
pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)>
pub fn iter_resources(&self) -> impl Iterator<Item = (&ComponentInfo, Ptr<'_>)>
Iterates over all resources in the world.
The returned iterator provides lifetimed, but type-unsafe pointers. Actually reading the contents of each resource will require the use of unsafe code.
§Examples
§Printing the size of all resources
let mut total = 0;
for (info, _) in world.iter_resources() {
println!("Resource: {}", info.name());
println!("Size: {} bytes", info.layout().size());
total += info.layout().size();
}
println!("Total size: {} bytes", total);§Dynamically running closures for resources matching specific TypeIds
// In this example, `A` and `B` are resources. We deliberately do not use the
// `bevy_reflect` crate here to showcase the low-level [`Ptr`] usage. You should
// probably use something like `ReflectFromPtr` in a real-world scenario.
// Create the hash map that will store the closures for each resource type
let mut closures: HashMap<TypeId, Box<dyn Fn(&Ptr<'_>)>> = HashMap::default();
// Add closure for `A`
closures.insert(TypeId::of::<A>(), Box::new(|ptr| {
// SAFETY: We assert ptr is the same type of A with TypeId of A
let a = unsafe { &ptr.deref::<A>() };
// ... do something with `a` here
}));
// Add closure for `B`
closures.insert(TypeId::of::<B>(), Box::new(|ptr| {
// SAFETY: We assert ptr is the same type of B with TypeId of B
let b = unsafe { &ptr.deref::<B>() };
// ... do something with `b` here
}));
// Iterate all resources, in order to run the closures for each matching resource type
for (info, ptr) in world.iter_resources() {
let Some(type_id) = info.type_id() else {
// It's possible for resources to not have a `TypeId` (e.g. non-Rust resources
// dynamically inserted via a scripting language) in which case we can't match them.
continue;
};
let Some(closure) = closures.get(&type_id) else {
// No closure for this resource type, skip it.
continue;
};
// Run the closure for the resource
closure(&ptr);
}pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>>
pub fn get_non_send_by_id(&self, component_id: ComponentId) -> Option<Ptr<'_>>
Gets a pointer to !Send data with the id ComponentId if it exists.
The returned pointer must not be used to modify the resource, and must not be
dereferenced after the immutable borrow of the World ends.
You should prefer to use the typed API World::get_non_send where possible and only
use this in cases where the actual types are not known at compile time.
§Panics
This function will panic if it isn’t called from the same thread that the data was inserted from.
pub fn get_by_id(
&self,
entity: Entity,
component_id: ComponentId,
) -> Option<Ptr<'_>>
pub fn get_by_id( &self, entity: Entity, component_id: ComponentId, ) -> Option<Ptr<'_>>
Retrieves an immutable untyped reference to the given entity’s Component of the given ComponentId.
Returns None if the entity does not have a Component of the given type.
You should prefer to use the typed API World::get_mut where possible and only
use this in cases where the actual types are not known at compile time.
§Panics
This function will panic if it isn’t called from the same thread that the resource was inserted from.
Trait Implementations§
§impl<'w> Deref for DeferredWorld<'w>
impl<'w> Deref for DeferredWorld<'w>
§impl<'w> From<&'w mut World> for DeferredWorld<'w>
impl<'w> From<&'w mut World> for DeferredWorld<'w>
§fn from(world: &'w mut World) -> DeferredWorld<'w>
fn from(world: &'w mut World) -> DeferredWorld<'w>
§impl<'w> SystemParam for DeferredWorld<'w>
impl<'w> SystemParam for DeferredWorld<'w>
§type Item<'world, 'state> = DeferredWorld<'world>
type Item<'world, 'state> = DeferredWorld<'world>
Self, instantiated with new lifetimes. Read more§fn init_state(_world: &mut World) -> <DeferredWorld<'w> as SystemParam>::State
fn init_state(_world: &mut World) -> <DeferredWorld<'w> as SystemParam>::State
State.§fn init_access(
_state: &<DeferredWorld<'w> as SystemParam>::State,
system_meta: &mut SystemMeta,
component_access_set: &mut FilteredAccessSet,
_world: &mut World,
)
fn init_access( _state: &<DeferredWorld<'w> as SystemParam>::State, system_meta: &mut SystemMeta, component_access_set: &mut FilteredAccessSet, _world: &mut World, )
§unsafe fn get_param<'world, 'state>(
_state: &'state mut <DeferredWorld<'w> as SystemParam>::State,
_system_meta: &SystemMeta,
world: UnsafeWorldCell<'world>,
_change_tick: Tick,
) -> Result<<DeferredWorld<'w> as SystemParam>::Item<'world, 'state>, SystemParamValidationError>
unsafe fn get_param<'world, 'state>( _state: &'state mut <DeferredWorld<'w> as SystemParam>::State, _system_meta: &SystemMeta, world: UnsafeWorldCell<'world>, _change_tick: Tick, ) -> Result<<DeferredWorld<'w> as SystemParam>::Item<'world, 'state>, SystemParamValidationError>
SystemParamFunction. Read more§fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
SystemParam’s state.
This is used to apply Commands during ApplyDeferred.§fn queue(
state: &mut Self::State,
system_meta: &SystemMeta,
world: DeferredWorld<'_>,
)
fn queue( state: &mut Self::State, system_meta: &SystemMeta, world: DeferredWorld<'_>, )
ApplyDeferred.Auto Trait Implementations§
impl<'w> Freeze for DeferredWorld<'w>
impl<'w> !RefUnwindSafe for DeferredWorld<'w>
impl<'w> Send for DeferredWorld<'w>
impl<'w> Sync for DeferredWorld<'w>
impl<'w> Unpin for DeferredWorld<'w>
impl<'w> UnsafeUnpin for DeferredWorld<'w>
impl<'w> !UnwindSafe for DeferredWorld<'w>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> Conv for T
impl<T> Conv for T
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.§impl<T> DowncastSend for T
impl<T> DowncastSend for T
§impl<T> FmtForward for T
impl<T> FmtForward for T
§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.§fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read more§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read more§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§impl<T> Tap for T
impl<T> Tap for T
§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read more§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read more§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read more§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read more§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read more§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read more§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.