pub struct EntityWorldMut<'w> { /* private fields */ }Expand description
A mutable reference to a particular Entity, and the entire world.
This is essentially a performance-optimized (Entity, &mut World) tuple,
which caches the EntityLocation to reduce duplicate lookups.
Since this type provides mutable access to the entire world, only one
EntityWorldMut can exist at a time for a given world.
See also EntityMut, which allows disjoint mutable access to multiple
entities at once. Unlike EntityMut, this type allows adding and
removing components, and despawning the entity.
Implementations§
Source§impl<'w> EntityWorldMut<'w>
impl<'w> EntityWorldMut<'w>
Sourcepub fn id(&self) -> Entity
pub fn id(&self) -> Entity
Returns the ID of the current entity.
Examples found in repository?
47fn main() {
48 let mut world = World::new();
49 let mut lines = std::io::stdin().lines();
50 let mut component_names = HashMap::<String, ComponentId>::new();
51 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
52
53 println!("{PROMPT}");
54 loop {
55 print!("\n> ");
56 let _ = std::io::stdout().flush();
57 let Some(Ok(line)) = lines.next() else {
58 return;
59 };
60
61 if line.is_empty() {
62 return;
63 };
64
65 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
66 match &line.chars().next() {
67 Some('c') => println!("{COMPONENT_PROMPT}"),
68 Some('s') => println!("{ENTITY_PROMPT}"),
69 Some('q') => println!("{QUERY_PROMPT}"),
70 _ => println!("{PROMPT}"),
71 }
72 continue;
73 };
74
75 match &first[0..1] {
76 "c" => {
77 rest.split(',').for_each(|component| {
78 let mut component = component.split_whitespace();
79 let Some(name) = component.next() else {
80 return;
81 };
82 let size = match component.next().map(str::parse) {
83 Some(Ok(size)) => size,
84 _ => 0,
85 };
86 // Register our new component to the world with a layout specified by it's size
87 // SAFETY: [u64] is Send + Sync
88 let id = world.register_component_with_descriptor(unsafe {
89 ComponentDescriptor::new_with_layout(
90 name.to_string(),
91 StorageType::Table,
92 Layout::array::<u64>(size).unwrap(),
93 None,
94 )
95 });
96 let Some(info) = world.components().get_info(id) else {
97 return;
98 };
99 component_names.insert(name.to_string(), id);
100 component_info.insert(id, info.clone());
101 println!("Component {} created with id: {:?}", name, id.index());
102 });
103 }
104 "s" => {
105 let mut to_insert_ids = Vec::new();
106 let mut to_insert_data = Vec::new();
107 rest.split(',').for_each(|component| {
108 let mut component = component.split_whitespace();
109 let Some(name) = component.next() else {
110 return;
111 };
112
113 // Get the id for the component with the given name
114 let Some(&id) = component_names.get(name) else {
115 println!("Component {name} does not exist");
116 return;
117 };
118
119 // Calculate the length for the array based on the layout created for this component id
120 let info = world.components().get_info(id).unwrap();
121 let len = info.layout().size() / size_of::<u64>();
122 let mut values: Vec<u64> = component
123 .take(len)
124 .filter_map(|value| value.parse::<u64>().ok())
125 .collect();
126 values.resize(len, 0);
127
128 // Collect the id and array to be inserted onto our entity
129 to_insert_ids.push(id);
130 to_insert_data.push(values);
131 });
132
133 let mut entity = world.spawn_empty();
134
135 // Construct an `OwningPtr` for each component in `to_insert_data`
136 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
137
138 // SAFETY:
139 // - Component ids have been taken from the same world
140 // - Each array is created to the layout specified in the world
141 unsafe {
142 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
143 }
144
145 println!("Entity spawned with id: {:?}", entity.id());
146 }
147 "q" => {
148 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
149 parse_query(rest, &mut builder, &component_names);
150 let mut query = builder.build();
151
152 query.iter_mut(&mut world).for_each(|filtered_entity| {
153 #[allow(deprecated)]
154 let terms = filtered_entity
155 .access()
156 .component_reads_and_writes()
157 .0
158 .map(|id| {
159 let ptr = filtered_entity.get_by_id(id).unwrap();
160 let info = component_info.get(&id).unwrap();
161 let len = info.layout().size() / size_of::<u64>();
162
163 // SAFETY:
164 // - All components are created with layout [u64]
165 // - len is calculated from the component descriptor
166 let data = unsafe {
167 std::slice::from_raw_parts_mut(
168 ptr.assert_unique().as_ptr().cast::<u64>(),
169 len,
170 )
171 };
172
173 // If we have write access, increment each value once
174 if filtered_entity.access().has_component_write(id) {
175 data.iter_mut().for_each(|data| {
176 *data += 1;
177 });
178 }
179
180 format!("{}: {:?}", info.name(), data[0..len].to_vec())
181 })
182 .collect::<Vec<_>>()
183 .join(", ");
184
185 println!("{:?}: {}", filtered_entity.id(), terms);
186 });
187 }
188 _ => continue,
189 }
190 }
191}Sourcepub fn location(&self) -> EntityLocation
pub fn location(&self) -> EntityLocation
Gets metadata indicating the location where the current entity is stored.
Sourcepub fn archetype(&self) -> &Archetype
pub fn archetype(&self) -> &Archetype
Returns the archetype that the current entity belongs to.
Sourcepub fn contains<T>(&self) -> boolwhere
T: Component,
pub fn contains<T>(&self) -> boolwhere
T: Component,
Returns true if the current entity has a component of type T.
Otherwise, this returns false.
§Notes
If you do not know the concrete type of a component, consider using
Self::contains_id or Self::contains_type_id.
Sourcepub fn contains_id(&self, component_id: ComponentId) -> bool
pub fn contains_id(&self, component_id: ComponentId) -> bool
Returns true if the current entity has a component identified by component_id.
Otherwise, this returns false.
§Notes
- If you know the concrete type of the component, you should prefer
Self::contains. - If you know the component’s
TypeIdbut not itsComponentId, consider usingSelf::contains_type_id.
Sourcepub fn contains_type_id(&self, type_id: TypeId) -> bool
pub fn contains_type_id(&self, type_id: TypeId) -> bool
Returns true if the current entity has a component with the type identified by type_id.
Otherwise, this returns false.
§Notes
- If you know the concrete type of the component, you should prefer
Self::contains. - If you have a
ComponentIdinstead of aTypeId, consider usingSelf::contains_id.
Sourcepub fn get<T>(&self) -> Option<&T>where
T: Component,
pub fn get<T>(&self) -> Option<&T>where
T: Component,
Gets access to the component of type T for the current entity.
Returns None if the entity does not have a component of type T.
Sourcepub fn components<Q>(&self) -> <Q as WorldQuery>::Item<'_>where
Q: ReadOnlyQueryData,
pub fn components<Q>(&self) -> <Q as WorldQuery>::Item<'_>where
Q: ReadOnlyQueryData,
Returns read-only components for the current entity that match the query Q.
§Panics
If the entity does not have the components required by the query Q.
Sourcepub fn get_components<Q>(&self) -> Option<<Q as WorldQuery>::Item<'_>>where
Q: ReadOnlyQueryData,
pub fn get_components<Q>(&self) -> Option<<Q as WorldQuery>::Item<'_>>where
Q: ReadOnlyQueryData,
Returns read-only components for the current entity that match the query Q,
or None if the entity does not have the components required by the query Q.
Sourcepub fn into_borrow<T>(self) -> Option<&'w T>where
T: Component,
pub fn into_borrow<T>(self) -> Option<&'w T>where
T: Component,
Consumes self and gets access to the component of type T with
the world 'w lifetime for the current entity.
Returns None if the entity does not have a component of type T.
Sourcepub fn get_ref<T>(&self) -> Option<Ref<'_, T>>where
T: Component,
pub fn get_ref<T>(&self) -> Option<Ref<'_, T>>where
T: Component,
Gets access to the component of type T for the current entity,
including change detection information as a Ref.
Returns None if the entity does not have a component of type T.
Sourcepub fn into_ref<T>(self) -> Option<Ref<'w, T>>where
T: Component,
pub fn into_ref<T>(self) -> Option<Ref<'w, T>>where
T: Component,
Consumes self and gets access to the component of type T
with the world 'w lifetime for the current entity,
including change detection information as a Ref.
Returns None if the entity does not have a component of type T.
Sourcepub fn get_mut<T>(&mut self) -> Option<Mut<'_, T>>where
T: Component,
pub fn get_mut<T>(&mut self) -> Option<Mut<'_, T>>where
T: Component,
Gets mutable access to the component of type T for the current entity.
Returns None if the entity does not have a component of type T.
Sourcepub fn into_mut<T>(self) -> Option<Mut<'w, T>>where
T: Component,
pub fn into_mut<T>(self) -> Option<Mut<'w, T>>where
T: Component,
Consumes self and gets mutable access to the component of type T
with the world 'w lifetime for the current entity.
Returns None if the entity does not have a component of type T.
Sourcepub fn get_change_ticks<T>(&self) -> Option<ComponentTicks>where
T: Component,
pub fn get_change_ticks<T>(&self) -> Option<ComponentTicks>where
T: Component,
Retrieves the change ticks for the given component. This can be useful for implementing change detection in custom runtimes.
Sourcepub fn get_change_ticks_by_id(
&self,
component_id: ComponentId,
) -> Option<ComponentTicks>
pub fn get_change_ticks_by_id( &self, component_id: ComponentId, ) -> Option<ComponentTicks>
Retrieves the change ticks for the given ComponentId. This can be useful for implementing change
detection in custom runtimes.
You should prefer to use the typed API EntityWorldMut::get_change_ticks where possible and only
use this in cases where the actual component types are not known at
compile time.
Sourcepub fn get_by_id<F>(
&self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Ref<'_>, EntityComponentError>where
F: DynamicComponentFetch,
pub fn get_by_id<F>(
&self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Ref<'_>, EntityComponentError>where
F: DynamicComponentFetch,
Returns untyped read-only reference(s) to component(s) for the
current entity, based on the given ComponentIds.
You should prefer to use the typed API EntityWorldMut::get where
possible and only use this in cases where the actual component types
are not known at compile time.
Unlike EntityWorldMut::get, this returns untyped reference(s) to
component(s), and it’s the job of the caller to ensure the correct
type(s) are dereferenced (if necessary).
§Errors
Returns EntityComponentError::MissingComponent if the entity does
not have a component.
§Examples
For examples on how to use this method, see EntityRef::get_by_id.
Sourcepub fn into_borrow_by_id<F>(
self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Ref<'w>, EntityComponentError>where
F: DynamicComponentFetch,
pub fn into_borrow_by_id<F>(
self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Ref<'w>, EntityComponentError>where
F: DynamicComponentFetch,
Consumes self and returns untyped read-only reference(s) to
component(s) with lifetime 'w for the current entity, based on the
given ComponentIds.
You should prefer to use the typed API EntityWorldMut::into_borrow
where possible and only use this in cases where the actual component
types are not known at compile time.
Unlike EntityWorldMut::into_borrow, this returns untyped reference(s) to
component(s), and it’s the job of the caller to ensure the correct
type(s) are dereferenced (if necessary).
§Errors
Returns EntityComponentError::MissingComponent if the entity does
not have a component.
§Examples
For examples on how to use this method, see EntityRef::get_by_id.
Sourcepub fn get_mut_by_id<F>(
&mut self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Mut<'_>, EntityComponentError>where
F: DynamicComponentFetch,
pub fn get_mut_by_id<F>(
&mut self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Mut<'_>, EntityComponentError>where
F: DynamicComponentFetch,
Returns untyped mutable reference(s) to component(s) for
the current entity, based on the given ComponentIds.
You should prefer to use the typed API EntityWorldMut::get_mut where
possible and only use this in cases where the actual component types
are not known at compile time.
Unlike EntityWorldMut::get_mut, this returns untyped reference(s) to
component(s), and it’s the job of the caller to ensure the correct
type(s) are dereferenced (if necessary).
§Errors
- Returns
EntityComponentError::MissingComponentif the entity does not have a component. - Returns
EntityComponentError::AliasedMutabilityif a component is requested multiple times.
§Examples
For examples on how to use this method, see EntityMut::get_mut_by_id.
Sourcepub fn into_mut_by_id<F>(
self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Mut<'w>, EntityComponentError>where
F: DynamicComponentFetch,
pub fn into_mut_by_id<F>(
self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Mut<'w>, EntityComponentError>where
F: DynamicComponentFetch,
Consumes self and returns untyped mutable reference(s)
to component(s) with lifetime 'w for the current entity, based on the
given ComponentIds.
You should prefer to use the typed API EntityWorldMut::into_mut where
possible and only use this in cases where the actual component types
are not known at compile time.
Unlike EntityWorldMut::into_mut, this returns untyped reference(s) to
component(s), and it’s the job of the caller to ensure the correct
type(s) are dereferenced (if necessary).
§Errors
- Returns
EntityComponentError::MissingComponentif the entity does not have a component. - Returns
EntityComponentError::AliasedMutabilityif a component is requested multiple times.
§Examples
For examples on how to use this method, see EntityMut::get_mut_by_id.
Sourcepub fn insert<T>(&mut self, bundle: T) -> &mut EntityWorldMut<'w>where
T: Bundle,
pub fn insert<T>(&mut self, bundle: T) -> &mut EntityWorldMut<'w>where
T: Bundle,
Adds a Bundle of components to the entity.
This will overwrite any previous value(s) of the same component type.
Examples found in repository?
52fn spawn_tasks(mut commands: Commands) {
53 let thread_pool = AsyncComputeTaskPool::get();
54 for x in 0..NUM_CUBES {
55 for y in 0..NUM_CUBES {
56 for z in 0..NUM_CUBES {
57 // Spawn new task on the AsyncComputeTaskPool; the task will be
58 // executed in the background, and the Task future returned by
59 // spawn() can be used to poll for the result
60 let entity = commands.spawn_empty().id();
61 let task = thread_pool.spawn(async move {
62 let duration = Duration::from_secs_f32(rand::thread_rng().gen_range(0.05..5.0));
63
64 // Pretend this is a time-intensive function. :)
65 async_std::task::sleep(duration).await;
66
67 // Such hard work, all done!
68 let transform = Transform::from_xyz(x as f32, y as f32, z as f32);
69 let mut command_queue = CommandQueue::default();
70
71 // we use a raw command queue to pass a FnOnce(&mut World) back to be
72 // applied in a deferred manner.
73 command_queue.push(move |world: &mut World| {
74 let (box_mesh_handle, box_material_handle) = {
75 let mut system_state = SystemState::<(
76 Res<BoxMeshHandle>,
77 Res<BoxMaterialHandle>,
78 )>::new(world);
79 let (box_mesh_handle, box_material_handle) =
80 system_state.get_mut(world);
81
82 (box_mesh_handle.clone(), box_material_handle.clone())
83 };
84
85 world
86 .entity_mut(entity)
87 // Add our new `Mesh3d` and `MeshMaterial3d` to our tagged entity
88 .insert((
89 Mesh3d(box_mesh_handle),
90 MeshMaterial3d(box_material_handle),
91 transform,
92 ))
93 // Task is complete, so remove task component from entity
94 .remove::<ComputeTransform>();
95 });
96
97 command_queue
98 });
99
100 // Spawn new entity and add our new task as a component
101 commands.entity(entity).insert(ComputeTransform(task));
102 }
103 }
104 }
105}Sourcepub fn insert_if_new<T>(&mut self, bundle: T) -> &mut EntityWorldMut<'w>where
T: Bundle,
pub fn insert_if_new<T>(&mut self, bundle: T) -> &mut EntityWorldMut<'w>where
T: Bundle,
Adds a Bundle of components to the entity without overwriting.
This will leave any previous value(s) of the same component type unchanged.
Sourcepub unsafe fn insert_by_id(
&mut self,
component_id: ComponentId,
component: OwningPtr<'_>,
) -> &mut EntityWorldMut<'w>
pub unsafe fn insert_by_id( &mut self, component_id: ComponentId, component: OwningPtr<'_>, ) -> &mut EntityWorldMut<'w>
Inserts a dynamic Component into the entity.
This will overwrite any previous value(s) of the same component type.
You should prefer to use the typed API EntityWorldMut::insert where possible.
§Safety
ComponentIdmust be from the same world asEntityWorldMutOwningPtrmust be a valid reference to the type represented byComponentId
Sourcepub unsafe fn insert_by_ids<'a, I>(
&mut self,
component_ids: &[ComponentId],
iter_components: I,
) -> &mut EntityWorldMut<'w>
pub unsafe fn insert_by_ids<'a, I>( &mut self, component_ids: &[ComponentId], iter_components: I, ) -> &mut EntityWorldMut<'w>
Inserts a dynamic Bundle into the entity.
This will overwrite any previous value(s) of the same component type.
You should prefer to use the typed API EntityWorldMut::insert where possible.
If your Bundle only has one component, use the cached API EntityWorldMut::insert_by_id.
If possible, pass a sorted slice of ComponentId to maximize caching potential.
§Safety
- Each
ComponentIdmust be from the same world asEntityWorldMut - Each
OwningPtrmust be a valid reference to the type represented byComponentId
Examples found in repository?
47fn main() {
48 let mut world = World::new();
49 let mut lines = std::io::stdin().lines();
50 let mut component_names = HashMap::<String, ComponentId>::new();
51 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
52
53 println!("{PROMPT}");
54 loop {
55 print!("\n> ");
56 let _ = std::io::stdout().flush();
57 let Some(Ok(line)) = lines.next() else {
58 return;
59 };
60
61 if line.is_empty() {
62 return;
63 };
64
65 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
66 match &line.chars().next() {
67 Some('c') => println!("{COMPONENT_PROMPT}"),
68 Some('s') => println!("{ENTITY_PROMPT}"),
69 Some('q') => println!("{QUERY_PROMPT}"),
70 _ => println!("{PROMPT}"),
71 }
72 continue;
73 };
74
75 match &first[0..1] {
76 "c" => {
77 rest.split(',').for_each(|component| {
78 let mut component = component.split_whitespace();
79 let Some(name) = component.next() else {
80 return;
81 };
82 let size = match component.next().map(str::parse) {
83 Some(Ok(size)) => size,
84 _ => 0,
85 };
86 // Register our new component to the world with a layout specified by it's size
87 // SAFETY: [u64] is Send + Sync
88 let id = world.register_component_with_descriptor(unsafe {
89 ComponentDescriptor::new_with_layout(
90 name.to_string(),
91 StorageType::Table,
92 Layout::array::<u64>(size).unwrap(),
93 None,
94 )
95 });
96 let Some(info) = world.components().get_info(id) else {
97 return;
98 };
99 component_names.insert(name.to_string(), id);
100 component_info.insert(id, info.clone());
101 println!("Component {} created with id: {:?}", name, id.index());
102 });
103 }
104 "s" => {
105 let mut to_insert_ids = Vec::new();
106 let mut to_insert_data = Vec::new();
107 rest.split(',').for_each(|component| {
108 let mut component = component.split_whitespace();
109 let Some(name) = component.next() else {
110 return;
111 };
112
113 // Get the id for the component with the given name
114 let Some(&id) = component_names.get(name) else {
115 println!("Component {name} does not exist");
116 return;
117 };
118
119 // Calculate the length for the array based on the layout created for this component id
120 let info = world.components().get_info(id).unwrap();
121 let len = info.layout().size() / size_of::<u64>();
122 let mut values: Vec<u64> = component
123 .take(len)
124 .filter_map(|value| value.parse::<u64>().ok())
125 .collect();
126 values.resize(len, 0);
127
128 // Collect the id and array to be inserted onto our entity
129 to_insert_ids.push(id);
130 to_insert_data.push(values);
131 });
132
133 let mut entity = world.spawn_empty();
134
135 // Construct an `OwningPtr` for each component in `to_insert_data`
136 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
137
138 // SAFETY:
139 // - Component ids have been taken from the same world
140 // - Each array is created to the layout specified in the world
141 unsafe {
142 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
143 }
144
145 println!("Entity spawned with id: {:?}", entity.id());
146 }
147 "q" => {
148 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
149 parse_query(rest, &mut builder, &component_names);
150 let mut query = builder.build();
151
152 query.iter_mut(&mut world).for_each(|filtered_entity| {
153 #[allow(deprecated)]
154 let terms = filtered_entity
155 .access()
156 .component_reads_and_writes()
157 .0
158 .map(|id| {
159 let ptr = filtered_entity.get_by_id(id).unwrap();
160 let info = component_info.get(&id).unwrap();
161 let len = info.layout().size() / size_of::<u64>();
162
163 // SAFETY:
164 // - All components are created with layout [u64]
165 // - len is calculated from the component descriptor
166 let data = unsafe {
167 std::slice::from_raw_parts_mut(
168 ptr.assert_unique().as_ptr().cast::<u64>(),
169 len,
170 )
171 };
172
173 // If we have write access, increment each value once
174 if filtered_entity.access().has_component_write(id) {
175 data.iter_mut().for_each(|data| {
176 *data += 1;
177 });
178 }
179
180 format!("{}: {:?}", info.name(), data[0..len].to_vec())
181 })
182 .collect::<Vec<_>>()
183 .join(", ");
184
185 println!("{:?}: {}", filtered_entity.id(), terms);
186 });
187 }
188 _ => continue,
189 }
190 }
191}Sourcepub fn take<T>(&mut self) -> Option<T>where
T: Bundle,
pub fn take<T>(&mut self) -> Option<T>where
T: Bundle,
Removes all components in the Bundle from the entity and returns their previous values.
Note: If the entity does not have every component in the bundle, this method will not remove any of them.
Sourcepub fn remove<T>(&mut self) -> &mut EntityWorldMut<'w>where
T: Bundle,
pub fn remove<T>(&mut self) -> &mut EntityWorldMut<'w>where
T: Bundle,
Removes any components in the Bundle from the entity.
See EntityCommands::remove for more details.
Examples found in repository?
52fn spawn_tasks(mut commands: Commands) {
53 let thread_pool = AsyncComputeTaskPool::get();
54 for x in 0..NUM_CUBES {
55 for y in 0..NUM_CUBES {
56 for z in 0..NUM_CUBES {
57 // Spawn new task on the AsyncComputeTaskPool; the task will be
58 // executed in the background, and the Task future returned by
59 // spawn() can be used to poll for the result
60 let entity = commands.spawn_empty().id();
61 let task = thread_pool.spawn(async move {
62 let duration = Duration::from_secs_f32(rand::thread_rng().gen_range(0.05..5.0));
63
64 // Pretend this is a time-intensive function. :)
65 async_std::task::sleep(duration).await;
66
67 // Such hard work, all done!
68 let transform = Transform::from_xyz(x as f32, y as f32, z as f32);
69 let mut command_queue = CommandQueue::default();
70
71 // we use a raw command queue to pass a FnOnce(&mut World) back to be
72 // applied in a deferred manner.
73 command_queue.push(move |world: &mut World| {
74 let (box_mesh_handle, box_material_handle) = {
75 let mut system_state = SystemState::<(
76 Res<BoxMeshHandle>,
77 Res<BoxMaterialHandle>,
78 )>::new(world);
79 let (box_mesh_handle, box_material_handle) =
80 system_state.get_mut(world);
81
82 (box_mesh_handle.clone(), box_material_handle.clone())
83 };
84
85 world
86 .entity_mut(entity)
87 // Add our new `Mesh3d` and `MeshMaterial3d` to our tagged entity
88 .insert((
89 Mesh3d(box_mesh_handle),
90 MeshMaterial3d(box_material_handle),
91 transform,
92 ))
93 // Task is complete, so remove task component from entity
94 .remove::<ComputeTransform>();
95 });
96
97 command_queue
98 });
99
100 // Spawn new entity and add our new task as a component
101 commands.entity(entity).insert(ComputeTransform(task));
102 }
103 }
104 }
105}Sourcepub fn remove_with_requires<T>(&mut self) -> &mut EntityWorldMut<'w>where
T: Bundle,
pub fn remove_with_requires<T>(&mut self) -> &mut EntityWorldMut<'w>where
T: Bundle,
Removes all components in the Bundle and remove all required components for each component in the bundle
Sourcepub fn retain<T>(&mut self) -> &mut EntityWorldMut<'w>where
T: Bundle,
pub fn retain<T>(&mut self) -> &mut EntityWorldMut<'w>where
T: Bundle,
Removes any components except those in the Bundle (and its Required Components) from the entity.
See EntityCommands::retain for more details.
Sourcepub fn remove_by_id(
&mut self,
component_id: ComponentId,
) -> &mut EntityWorldMut<'w>
pub fn remove_by_id( &mut self, component_id: ComponentId, ) -> &mut EntityWorldMut<'w>
Removes a dynamic Component from the entity if it exists.
You should prefer to use the typed API EntityWorldMut::remove where possible.
§Panics
Panics if the provided ComponentId does not exist in the World.
Sourcepub fn clear(&mut self) -> &mut EntityWorldMut<'w>
pub fn clear(&mut self) -> &mut EntityWorldMut<'w>
Removes all components associated with the entity.
Sourcepub fn despawn(self)
pub fn despawn(self)
Despawns the current entity.
See World::despawn for more details.
Sourcepub fn flush(self) -> Entity
pub fn flush(self) -> Entity
Ensures any commands triggered by the actions of Self are applied, equivalent to World::flush
Sourcepub fn world(&self) -> &World
pub fn world(&self) -> &World
Gets read-only access to the world that the current entity belongs to.
Sourcepub unsafe fn world_mut(&mut self) -> &mut World
pub unsafe fn world_mut(&mut self) -> &mut World
Returns this entity’s world.
See EntityWorldMut::world_scope or EntityWorldMut::into_world_mut for a safe alternative.
§Safety
Caller must not modify the world in a way that changes the current entity’s location
If the caller does do something that could change the location, self.update_location()
must be called before using any other methods on this EntityWorldMut.
Sourcepub fn into_world_mut(self) -> &'w mut World
pub fn into_world_mut(self) -> &'w mut World
Returns this entity’s World, consuming itself.
Sourcepub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U
pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U
Gives mutable access to this entity’s World in a temporary scope.
This is a safe alternative to using EntityWorldMut::world_mut.
§Examples
#[derive(Resource, Default, Clone, Copy)]
struct R(u32);
// This closure gives us temporary access to the world.
let new_r = entity.world_scope(|world: &mut World| {
// Mutate the world while we have access to it.
let mut r = world.resource_mut::<R>();
r.0 += 1;
// Return a value from the world before giving it back to the `EntityWorldMut`.
*r
});Sourcepub fn update_location(&mut self)
pub fn update_location(&mut self)
Updates the internal entity location to match the current location in the internal
World.
This is only required when using the unsafe function EntityWorldMut::world_mut,
which enables the location to change.
Sourcepub fn entry<'a, T>(&'a mut self) -> Entry<'w, 'a, T>where
T: Component,
pub fn entry<'a, T>(&'a mut self) -> Entry<'w, 'a, T>where
T: Component,
Gets an Entry into the world for this entity and component for in-place manipulation.
The type parameter specifies which component to get.
§Examples
#[derive(Component, Default, Clone, Copy, Debug, PartialEq)]
struct Comp(u32);
let mut entity = world.spawn_empty();
entity.entry().or_insert_with(|| Comp(4));
assert_eq!(world.query::<&Comp>().single(&world).0, 4);
entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
assert_eq!(world.query::<&Comp>().single(&world).0, 5);Sourcepub fn trigger(&mut self, event: impl Event) -> &mut EntityWorldMut<'w>
pub fn trigger(&mut self, event: impl Event) -> &mut EntityWorldMut<'w>
Triggers the given event for this entity, which will run any observers watching for it.
Sourcepub fn observe<E, B, M>(
&mut self,
observer: impl IntoObserverSystem<E, B, M>,
) -> &mut EntityWorldMut<'w>
pub fn observe<E, B, M>( &mut self, observer: impl IntoObserverSystem<E, B, M>, ) -> &mut EntityWorldMut<'w>
Creates an Observer listening for events of type E targeting this entity.
In order to trigger the callback the entity must also match the query when the event is fired.
Trait Implementations§
Source§impl BuildChildren for EntityWorldMut<'_>
impl BuildChildren for EntityWorldMut<'_>
Source§type Builder<'a> = WorldChildBuilder<'a>
type Builder<'a> = WorldChildBuilder<'a>
Source§fn with_children(
&mut self,
spawn_children: impl FnOnce(&mut WorldChildBuilder<'_>),
) -> &mut EntityWorldMut<'_>
fn with_children( &mut self, spawn_children: impl FnOnce(&mut WorldChildBuilder<'_>), ) -> &mut EntityWorldMut<'_>
ChildBuild. Read moreSource§fn with_child<B>(&mut self, bundle: B) -> &mut EntityWorldMut<'_>where
B: Bundle,
fn with_child<B>(&mut self, bundle: B) -> &mut EntityWorldMut<'_>where
B: Bundle,
Source§fn add_child(&mut self, child: Entity) -> &mut EntityWorldMut<'_>
fn add_child(&mut self, child: Entity) -> &mut EntityWorldMut<'_>
Source§fn add_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'_>
fn add_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'_>
Source§fn insert_children(
&mut self,
index: usize,
children: &[Entity],
) -> &mut EntityWorldMut<'_>
fn insert_children( &mut self, index: usize, children: &[Entity], ) -> &mut EntityWorldMut<'_>
Source§fn remove_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'_>
fn remove_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'_>
Source§fn set_parent(&mut self, parent: Entity) -> &mut EntityWorldMut<'_>
fn set_parent(&mut self, parent: Entity) -> &mut EntityWorldMut<'_>
Source§fn remove_parent(&mut self) -> &mut EntityWorldMut<'_>
fn remove_parent(&mut self) -> &mut EntityWorldMut<'_>
Source§fn clear_children(&mut self) -> &mut EntityWorldMut<'_>
fn clear_children(&mut self) -> &mut EntityWorldMut<'_>
Children component will be removed if it exists, otherwise this does nothing.Source§fn replace_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'_>
fn replace_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'_>
Source§impl BuildChildrenTransformExt for EntityWorldMut<'_>
impl BuildChildrenTransformExt for EntityWorldMut<'_>
Source§fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityWorldMut<'_>
fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityWorldMut<'_>
GlobalTransform
by updating its Transform. Read moreSource§fn remove_parent_in_place(&mut self) -> &mut EntityWorldMut<'_>
fn remove_parent_in_place(&mut self) -> &mut EntityWorldMut<'_>
GlobalTransform
by updating its Transform to be equal to its current GlobalTransform. Read moreSource§impl<'w> DespawnRecursiveExt for EntityWorldMut<'w>
impl<'w> DespawnRecursiveExt for EntityWorldMut<'w>
Source§fn despawn_recursive(self)
fn despawn_recursive(self)
Despawns the provided entity and its children. This will emit warnings for any entity that does not exist.
Source§fn try_despawn_recursive(self)
fn try_despawn_recursive(self)
Despawns the provided entity and its children. This will not emit warnings.
Source§fn despawn_descendants(&mut self) -> &mut EntityWorldMut<'w>
fn despawn_descendants(&mut self) -> &mut EntityWorldMut<'w>
Source§fn try_despawn_descendants(&mut self) -> &mut EntityWorldMut<'w>
fn try_despawn_descendants(&mut self) -> &mut EntityWorldMut<'w>
Self::despawn_descendants but does not emit warningsSource§impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a>
impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a>
Source§fn from(value: &'a EntityWorldMut<'_>) -> EntityRef<'a>
fn from(value: &'a EntityWorldMut<'_>) -> EntityRef<'a>
Source§impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a>
impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a>
Source§fn from(entity: &'a EntityWorldMut<'_>) -> FilteredEntityRef<'a>
fn from(entity: &'a EntityWorldMut<'_>) -> FilteredEntityRef<'a>
Source§impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a>
impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a>
Source§fn from(value: &'a mut EntityWorldMut<'_>) -> EntityMut<'a>
fn from(value: &'a mut EntityWorldMut<'_>) -> EntityMut<'a>
Source§impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a>
impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a>
Source§fn from(entity: &'a mut EntityWorldMut<'_>) -> FilteredEntityMut<'a>
fn from(entity: &'a mut EntityWorldMut<'_>) -> FilteredEntityMut<'a>
Source§impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a>
impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a>
Source§fn from(entity: EntityWorldMut<'a>) -> FilteredEntityMut<'a>
fn from(entity: EntityWorldMut<'a>) -> FilteredEntityMut<'a>
Source§impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a>
impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a>
Source§fn from(entity: EntityWorldMut<'a>) -> FilteredEntityRef<'a>
fn from(entity: EntityWorldMut<'a>) -> FilteredEntityRef<'a>
Source§impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w>
impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w>
Source§fn from(value: EntityWorldMut<'w>) -> EntityMut<'w>
fn from(value: EntityWorldMut<'w>) -> EntityMut<'w>
Source§impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w>
impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w>
Source§fn from(entity_mut: EntityWorldMut<'w>) -> EntityRef<'w>
fn from(entity_mut: EntityWorldMut<'w>) -> EntityRef<'w>
Auto Trait Implementations§
impl<'w> Freeze for EntityWorldMut<'w>
impl<'w> !RefUnwindSafe for EntityWorldMut<'w>
impl<'w> Send for EntityWorldMut<'w>
impl<'w> Sync for EntityWorldMut<'w>
impl<'w> Unpin for EntityWorldMut<'w>
impl<'w> !UnwindSafe for EntityWorldMut<'w>
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T ShaderType for self. When used in AsBindGroup
derives, it is safe to assume that all images in self exist.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
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§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>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§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>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§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.Source§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.Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§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.Source§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.Source§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.Source§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.Source§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.Source§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.Source§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.Source§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.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§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 moreSource§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 moreSource§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
Source§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
Source§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.Source§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.Source§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.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> Tap for T
impl<T> Tap for T
Source§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 moreSource§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 moreSource§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 moreSource§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 moreSource§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 moreSource§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 moreSource§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.Source§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.Source§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.Source§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.Source§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.Source§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.Source§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.