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 with_children(
&mut self,
func: impl FnOnce(&mut RelatedSpawner<'_, ChildOf>),
) -> &mut EntityWorldMut<'w>
pub fn with_children( &mut self, func: impl FnOnce(&mut RelatedSpawner<'_, ChildOf>), ) -> &mut EntityWorldMut<'w>
Spawns children of this entity (with a ChildOf
relationship) by taking a function that operates on a ChildSpawner
.
See also with_related
.
Sourcepub fn add_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'w>
pub fn add_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'w>
Adds the given children to this entity
See also add_related
.
Sourcepub fn insert_children(
&mut self,
index: usize,
children: &[Entity],
) -> &mut EntityWorldMut<'w>
pub fn insert_children( &mut self, index: usize, children: &[Entity], ) -> &mut EntityWorldMut<'w>
Insert children at specific index.
See also insert_related
.
Sourcepub fn add_child(&mut self, child: Entity) -> &mut EntityWorldMut<'w>
pub fn add_child(&mut self, child: Entity) -> &mut EntityWorldMut<'w>
Adds the given child to this entity
See also add_related
.
Sourcepub fn remove_children(
&mut self,
children: &[Entity],
) -> &mut EntityWorldMut<'w>
pub fn remove_children( &mut self, children: &[Entity], ) -> &mut EntityWorldMut<'w>
Removes the relationship between this entity and the given entities.
Sourcepub fn replace_children(
&mut self,
children: &[Entity],
) -> &mut EntityWorldMut<'w>
pub fn replace_children( &mut self, children: &[Entity], ) -> &mut EntityWorldMut<'w>
Replaces all the related children with a new set of children.
Sourcepub fn replace_children_with_difference(
&mut self,
entities_to_unrelate: &[Entity],
entities_to_relate: &[Entity],
newly_related_entities: &[Entity],
) -> &mut EntityWorldMut<'w>
pub fn replace_children_with_difference( &mut self, entities_to_unrelate: &[Entity], entities_to_relate: &[Entity], newly_related_entities: &[Entity], ) -> &mut EntityWorldMut<'w>
Replaces all the related children with a new set of children.
§Warning
Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
Refer to Self::replace_related_with_difference
for a list of these invariants.
§Panics
Panics when debug assertions are enabled if an invariant is is broken and the command is executed.
Sourcepub fn with_child(&mut self, bundle: impl Bundle) -> &mut EntityWorldMut<'w>
pub fn with_child(&mut self, bundle: impl Bundle) -> &mut EntityWorldMut<'w>
Spawns the passed bundle and adds it to this entity as a child.
For efficient spawning of multiple children, use with_children
.
Sourcepub fn remove_parent(&mut self) -> &mut EntityWorldMut<'w>
👎Deprecated since 0.16.0: Use entity_mut.remove::<ChildOf>()
pub fn remove_parent(&mut self) -> &mut EntityWorldMut<'w>
Removes the ChildOf
component, if it exists.
Sourcepub fn set_parent(&mut self, parent: Entity) -> &mut EntityWorldMut<'w>
👎Deprecated since 0.16.0: Use entity_mut.insert(ChildOf(entity))
pub fn set_parent(&mut self, parent: Entity) -> &mut EntityWorldMut<'w>
Inserts the ChildOf
component with the given parent
entity, if it exists.
Source§impl<'w> EntityWorldMut<'w>
impl<'w> EntityWorldMut<'w>
Sourcepub fn insert_reflect(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut EntityWorldMut<'w>
pub fn insert_reflect( &mut self, component: Box<dyn PartialReflect>, ) -> &mut EntityWorldMut<'w>
Adds the given boxed reflect component or bundle to the entity using the reflection data in
AppTypeRegistry
.
This will overwrite any previous component(s) of the same type.
§Panics
- If the entity has been despawned while this
EntityWorldMut
is still alive. - If
AppTypeRegistry
does not have the reflection data for the givenComponent
orBundle
. - If the component or bundle data is invalid. See
PartialReflect::apply
for further details. - If
AppTypeRegistry
is not present in theWorld
.
§Note
Prefer to use the typed EntityWorldMut::insert
if possible. Adding a reflected component
is much slower.
Sourcepub fn insert_reflect_with_registry<T>(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut EntityWorldMut<'w>
pub fn insert_reflect_with_registry<T>( &mut self, component: Box<dyn PartialReflect>, ) -> &mut EntityWorldMut<'w>
Same as insert_reflect
, but using
the T
resource as type registry instead of AppTypeRegistry
.
This will overwrite any previous component(s) of the same type.
§Panics
- If the entity has been despawned while this
EntityWorldMut
is still alive. - If the given
Resource
does not have the reflection data for the givenComponent
orBundle
. - If the component or bundle data is invalid. See
PartialReflect::apply
for further details. - If the given
Resource
is not present in theWorld
.
Sourcepub fn remove_reflect(
&mut self,
component_type_path: Cow<'static, str>,
) -> &mut EntityWorldMut<'w>
pub fn remove_reflect( &mut self, component_type_path: Cow<'static, str>, ) -> &mut EntityWorldMut<'w>
Removes from the entity the component or bundle with the given type name registered in AppTypeRegistry
.
If the type is a bundle, it will remove any components in that bundle regardless if the entity contains all the components.
Does nothing if the type is a component and the entity does not have a component of the same type,
if the type is a bundle and the entity does not contain any of the components in the bundle,
or if AppTypeRegistry
does not contain the reflection data for the given component.
§Panics
- If the entity has been despawned while this
EntityWorldMut
is still alive. - If
AppTypeRegistry
is not present in theWorld
.
§Note
Prefer to use the typed EntityCommands::remove
if possible. Removing a reflected component
is much slower.
Sourcepub fn remove_reflect_with_registry<T>(
&mut self,
component_type_path: Cow<'static, str>,
) -> &mut EntityWorldMut<'w>
pub fn remove_reflect_with_registry<T>( &mut self, component_type_path: Cow<'static, str>, ) -> &mut EntityWorldMut<'w>
Same as remove_reflect
, but using
the T
resource as type registry instead of AppTypeRegistry
.
If the given type is a bundle, it will remove any components in that bundle regardless if the entity contains all the components.
Does nothing if the type is a component and the entity does not have a component of the same type,
if the type is a bundle and the entity does not contain any of the components in the bundle,
or if AppTypeRegistry
does not contain the reflection data for the given component.
§Panics
- If the entity has been despawned while this
EntityWorldMut
is still alive. - If
AppTypeRegistry
is not present in theWorld
.
Source§impl<'w> EntityWorldMut<'w>
impl<'w> EntityWorldMut<'w>
Spawns a entity related to this entity (with the R
relationship) by taking a bundle
Spawns entities related to this entity (with the R
relationship) by taking a function that operates on a RelatedSpawner
.
Relates the given entities to this entity with the relation R
.
See add_one_related
if you want relate only one entity.
Relates the given entities to this entity with the relation R
, starting at this particular index.
If the related
has duplicates, a related entity will take the index of its last occurrence in related
.
If the indices go out of bounds, they will be clamped into bounds.
This will not re-order existing related entities unless they are in related
.
§Example
use bevy_ecs::prelude::*;
let mut world = World::new();
let e0 = world.spawn_empty().id();
let e1 = world.spawn_empty().id();
let e2 = world.spawn_empty().id();
let e3 = world.spawn_empty().id();
let e4 = world.spawn_empty().id();
let mut main_entity = world.spawn_empty();
main_entity.add_related::<ChildOf>(&[e0, e1, e2, e2]);
main_entity.insert_related::<ChildOf>(1, &[e0, e3, e4, e4]);
let main_id = main_entity.id();
let relationship_source = main_entity.get::<Children>().unwrap().collection();
assert_eq!(relationship_source, &[e1, e0, e3, e2, e4]);
Removes the relation R
between this entity and the given entities.
Replaces all the related entities with a new set of entities.
Replaces all the related entities with a new set of entities.
This is a more efficient of Self::replace_related
which doesn’t allocate.
The passed in arguments must adhere to these invariants:
entities_to_unrelate
: A slice of entities to remove from the relationship source. Entities need not be related to this entity, but must not appear inentities_to_relate
entities_to_relate
: A slice of entities to relate to this entity. This must contain all entities that will remain related (i.e. not those inentities_to_unrelate
) plus the newly related entities.newly_related_entities
: A subset ofentities_to_relate
containing only entities not already related to this entity.- Slices must not contain any duplicates
§Warning
Violating these invariants may lead to panics, crashes or unpredictable engine behavior.
§Panics
Panics when debug assertions are enabled and any invariants are broken.
Relates the given entity to this with the relation R
.
See add_related
if you want to relate more than one entity.
Despawns entities that relate to this one via the given RelationshipTarget
.
This entity will not be despawned.
Sourcepub fn insert_recursive<S>(
&mut self,
bundle: impl Bundle + Clone,
) -> &mut EntityWorldMut<'w>where
S: RelationshipTarget,
pub fn insert_recursive<S>(
&mut self,
bundle: impl Bundle + Clone,
) -> &mut EntityWorldMut<'w>where
S: RelationshipTarget,
Inserts a component or bundle of components into the entity and all related entities,
traversing the relationship tracked in S
in a breadth-first manner.
§Warning
This method should only be called on relationships that form a tree-like structure. Any cycles will cause this method to loop infinitely.
Sourcepub fn remove_recursive<S, B>(&mut self) -> &mut EntityWorldMut<'w>where
S: RelationshipTarget,
B: Bundle,
pub fn remove_recursive<S, B>(&mut self) -> &mut EntityWorldMut<'w>where
S: RelationshipTarget,
B: Bundle,
Removes a component or bundle of components of type B
from the entity and all related entities,
traversing the relationship tracked in S
in a breadth-first manner.
§Warning
This method should only be called on relationships that form a tree-like structure. Any cycles will cause this method to loop infinitely.
Source§impl<'w> EntityWorldMut<'w>
impl<'w> EntityWorldMut<'w>
Sourcepub fn into_readonly(self) -> EntityRef<'w>
pub fn into_readonly(self) -> EntityRef<'w>
Consumes self
and returns read-only access to all of the entity’s
components, with the world 'w
lifetime.
Sourcepub fn as_readonly(&self) -> EntityRef<'_>
pub fn as_readonly(&self) -> EntityRef<'_>
Gets read-only access to all of the entity’s components.
Sourcepub fn into_mutable(self) -> EntityMut<'w>
pub fn into_mutable(self) -> EntityMut<'w>
Consumes self
and returns non-structural mutable access to all of the
entity’s components, with the world 'w
lifetime.
Sourcepub fn as_mutable(&mut self) -> EntityMut<'_>
pub fn as_mutable(&mut self) -> EntityMut<'_>
Gets non-structural mutable access to all of the entity’s components.
Sourcepub fn id(&self) -> Entity
pub fn id(&self) -> Entity
Returns the ID of the current entity.
Examples found in repository?
104fn demo_2(world: &mut World) {
105 // Setup our name index
106 world.init_resource::<NameIndex>();
107
108 // Spawn some entities!
109 let alyssa = world.spawn(Name("Alyssa")).id();
110 let javier = world.spawn(Name("Javier")).id();
111
112 // Check our index
113 let index = world.resource::<NameIndex>();
114
115 assert_eq!(index.get_entity("Alyssa"), Some(alyssa));
116 assert_eq!(index.get_entity("Javier"), Some(javier));
117
118 // Changing the name of an entity is also fully capture by our index
119 world.entity_mut(javier).insert(Name("Steven"));
120
121 // Javier changed their name to Steven
122 let steven = javier;
123
124 // Check our index
125 let index = world.resource::<NameIndex>();
126
127 assert_eq!(index.get_entity("Javier"), None);
128 assert_eq!(index.get_entity("Steven"), Some(steven));
129}
More examples
51fn main() {
52 let mut world = World::new();
53 let mut lines = std::io::stdin().lines();
54 let mut component_names = HashMap::<String, ComponentId>::new();
55 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57 println!("{PROMPT}");
58 loop {
59 print!("\n> ");
60 let _ = std::io::stdout().flush();
61 let Some(Ok(line)) = lines.next() else {
62 return;
63 };
64
65 if line.is_empty() {
66 return;
67 };
68
69 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70 match &line.chars().next() {
71 Some('c') => println!("{COMPONENT_PROMPT}"),
72 Some('s') => println!("{ENTITY_PROMPT}"),
73 Some('q') => println!("{QUERY_PROMPT}"),
74 _ => println!("{PROMPT}"),
75 }
76 continue;
77 };
78
79 match &first[0..1] {
80 "c" => {
81 rest.split(',').for_each(|component| {
82 let mut component = component.split_whitespace();
83 let Some(name) = component.next() else {
84 return;
85 };
86 let size = match component.next().map(str::parse) {
87 Some(Ok(size)) => size,
88 _ => 0,
89 };
90 // Register our new component to the world with a layout specified by it's size
91 // SAFETY: [u64] is Send + Sync
92 let id = world.register_component_with_descriptor(unsafe {
93 ComponentDescriptor::new_with_layout(
94 name.to_string(),
95 StorageType::Table,
96 Layout::array::<u64>(size).unwrap(),
97 None,
98 true,
99 ComponentCloneBehavior::Default,
100 )
101 });
102 let Some(info) = world.components().get_info(id) else {
103 return;
104 };
105 component_names.insert(name.to_string(), id);
106 component_info.insert(id, info.clone());
107 println!("Component {} created with id: {}", name, id.index());
108 });
109 }
110 "s" => {
111 let mut to_insert_ids = Vec::new();
112 let mut to_insert_data = Vec::new();
113 rest.split(',').for_each(|component| {
114 let mut component = component.split_whitespace();
115 let Some(name) = component.next() else {
116 return;
117 };
118
119 // Get the id for the component with the given name
120 let Some(&id) = component_names.get(name) else {
121 println!("Component {name} does not exist");
122 return;
123 };
124
125 // Calculate the length for the array based on the layout created for this component id
126 let info = world.components().get_info(id).unwrap();
127 let len = info.layout().size() / size_of::<u64>();
128 let mut values: Vec<u64> = component
129 .take(len)
130 .filter_map(|value| value.parse::<u64>().ok())
131 .collect();
132 values.resize(len, 0);
133
134 // Collect the id and array to be inserted onto our entity
135 to_insert_ids.push(id);
136 to_insert_data.push(values);
137 });
138
139 let mut entity = world.spawn_empty();
140
141 // Construct an `OwningPtr` for each component in `to_insert_data`
142 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144 // SAFETY:
145 // - Component ids have been taken from the same world
146 // - Each array is created to the layout specified in the world
147 unsafe {
148 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149 }
150
151 println!("Entity spawned with id: {}", entity.id());
152 }
153 "q" => {
154 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155 parse_query(rest, &mut builder, &component_names);
156 let mut query = builder.build();
157 query.iter_mut(&mut world).for_each(|filtered_entity| {
158 let terms = filtered_entity
159 .access()
160 .try_iter_component_access()
161 .unwrap()
162 .map(|component_access| {
163 let id = *component_access.index();
164 let ptr = filtered_entity.get_by_id(id).unwrap();
165 let info = component_info.get(&id).unwrap();
166 let len = info.layout().size() / size_of::<u64>();
167
168 // SAFETY:
169 // - All components are created with layout [u64]
170 // - len is calculated from the component descriptor
171 let data = unsafe {
172 std::slice::from_raw_parts_mut(
173 ptr.assert_unique().as_ptr().cast::<u64>(),
174 len,
175 )
176 };
177
178 // If we have write access, increment each value once
179 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180 data.iter_mut().for_each(|data| {
181 *data += 1;
182 });
183 }
184
185 format!("{}: {:?}", info.name(), data[0..len].to_vec())
186 })
187 .collect::<Vec<_>>()
188 .join(", ");
189
190 println!("{}: {}", filtered_entity.id(), terms);
191 });
192 }
193 _ => continue,
194 }
195 }
196}
Sourcepub fn location(&self) -> EntityLocation
pub fn location(&self) -> EntityLocation
Gets metadata indicating the location where the current entity is stored.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn archetype(&self) -> &Archetype
pub fn archetype(&self) -> &Archetype
Returns the archetype that the current entity belongs to.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
TypeId
but not itsComponentId
, consider usingSelf::contains_type_id
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
ComponentId
instead of aTypeId
, consider usingSelf::contains_id
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn components<Q>(&self) -> <Q as QueryData>::Item<'_>where
Q: ReadOnlyQueryData,
pub fn components<Q>(&self) -> <Q as QueryData>::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
or if the entity
has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn get_components<Q>(&self) -> Option<<Q as QueryData>::Item<'_>>where
Q: ReadOnlyQueryData,
pub fn get_components<Q>(&self) -> Option<<Q as QueryData>::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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn get_mut<T>(&mut self) -> Option<Mut<'_, T>>
pub fn get_mut<T>(&mut self) -> Option<Mut<'_, T>>
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
31fn demo_1(world: &mut World) {
32 // Immutable components can be inserted just like mutable components.
33 let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
34
35 // But where mutable components can be mutated...
36 let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
37 my_mutable_component.0 = true;
38
39 // ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
40 // is declared as immutable.
41 // let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
42
43 // Instead, you could take or replace the immutable component to update its value.
44 let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
45 my_immutable_component.0 = true;
46 entity.insert(my_immutable_component);
47}
Sourcepub fn modify_component<T, R>(
&mut self,
f: impl FnOnce(&mut T) -> R,
) -> Option<R>where
T: Component,
pub fn modify_component<T, R>(
&mut self,
f: impl FnOnce(&mut T) -> R,
) -> Option<R>where
T: Component,
Temporarily removes a Component
T
from this Entity
and runs the
provided closure on it, returning the result if T
was available.
This will trigger the OnRemove
and OnReplace
component hooks without
causing an archetype move.
This is most useful with immutable components, where removal and reinsertion is the only way to modify a value.
If you do not need to ensure the above hooks are triggered, and your component
is mutable, prefer using get_mut
.
§Examples
#[derive(Component, PartialEq, Eq, Debug)]
#[component(immutable)]
struct Foo(bool);
entity.modify_component(|foo: &mut Foo| {
foo.0 = true;
});
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn modify_component_by_id<R>(
&mut self,
component_id: ComponentId,
f: impl for<'a> FnOnce(MutUntyped<'a>) -> R,
) -> Option<R>
pub fn modify_component_by_id<R>( &mut self, component_id: ComponentId, f: impl for<'a> FnOnce(MutUntyped<'a>) -> R, ) -> Option<R>
Temporarily removes a Component
T
from this Entity
and runs the
provided closure on it, returning the result if T
was available.
This will trigger the OnRemove
and OnReplace
component hooks without
causing an archetype move.
This is most useful with immutable components, where removal and reinsertion is the only way to modify a value.
If you do not need to ensure the above hooks are triggered, and your component
is mutable, prefer using get_mut
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub unsafe fn get_mut_assume_mutable<T>(&mut self) -> Option<Mut<'_, T>>where
T: Component,
pub unsafe fn get_mut_assume_mutable<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
.
§Safety
T
must be a mutable component
Sourcepub fn into_mut<T>(self) -> Option<Mut<'w, T>>
pub fn into_mut<T>(self) -> Option<Mut<'w, T>>
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub unsafe fn into_mut_assume_mutable<T>(self) -> Option<Mut<'w, T>>where
T: Component,
pub unsafe fn into_mut_assume_mutable<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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
§Safety
T
must be a mutable component
Sourcepub 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.
Sourcepub fn resource_mut<R>(&mut self) -> Mut<'_, R>where
R: Resource,
pub fn resource_mut<R>(&mut self) -> Mut<'_, R>where
R: Resource,
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.
If you want to instead insert a value if the resource does not exist,
use get_resource_or_insert_with
.
Sourcepub 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
Sourcepub fn get_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>where
R: Resource,
pub fn get_resource_mut<R>(&mut self) -> Option<Mut<'_, R>>where
R: Resource,
Gets a mutable reference to the resource of the given type if it exists
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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 ComponentId
s.
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
136fn demo_3(world: &mut World) {
137 // This is a list of dynamic components we will create.
138 // The first item is the name of the component, and the second is the size
139 // in bytes.
140 let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
141
142 // This pipeline takes our component descriptions, registers them, and gets
143 // their ComponentId's.
144 let my_registered_components = my_dynamic_components
145 .into_iter()
146 .map(|(name, size)| {
147 // SAFETY:
148 // - No drop command is required
149 // - The component will store [u8; size], which is Send + Sync
150 let descriptor = unsafe {
151 ComponentDescriptor::new_with_layout(
152 name.to_string(),
153 StorageType::Table,
154 Layout::array::<u8>(size).unwrap(),
155 None,
156 false,
157 ComponentCloneBehavior::Default,
158 )
159 };
160
161 (name, size, descriptor)
162 })
163 .map(|(name, size, descriptor)| {
164 let component_id = world.register_component_with_descriptor(descriptor);
165
166 (name, size, component_id)
167 })
168 .collect::<Vec<(&str, usize, ComponentId)>>();
169
170 // Now that our components are registered, let's add them to an entity
171 let mut entity = world.spawn_empty();
172
173 for (_name, size, component_id) in &my_registered_components {
174 // We're just storing some zeroes for the sake of demonstration.
175 let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
176
177 OwningPtr::make(data, |ptr| {
178 // SAFETY:
179 // - ComponentId has been taken from the same world
180 // - Array is created to the layout specified in the world
181 unsafe {
182 entity.insert_by_id(*component_id, ptr);
183 }
184 });
185 }
186
187 for (_name, _size, component_id) in &my_registered_components {
188 // With immutable components, we can read the values...
189 assert!(entity.get_by_id(*component_id).is_ok());
190
191 // ...but we cannot gain a mutable reference.
192 assert!(entity.get_mut_by_id(*component_id).is_err());
193
194 // Instead, you must either remove or replace the value.
195 }
196}
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 ComponentId
s.
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
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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 ComponentId
s.
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::MissingComponent
if the entity does not have a component. - Returns
EntityComponentError::AliasedMutability
if a component is requested multiple times.
§Examples
For examples on how to use this method, see EntityMut::get_mut_by_id
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
136fn demo_3(world: &mut World) {
137 // This is a list of dynamic components we will create.
138 // The first item is the name of the component, and the second is the size
139 // in bytes.
140 let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
141
142 // This pipeline takes our component descriptions, registers them, and gets
143 // their ComponentId's.
144 let my_registered_components = my_dynamic_components
145 .into_iter()
146 .map(|(name, size)| {
147 // SAFETY:
148 // - No drop command is required
149 // - The component will store [u8; size], which is Send + Sync
150 let descriptor = unsafe {
151 ComponentDescriptor::new_with_layout(
152 name.to_string(),
153 StorageType::Table,
154 Layout::array::<u8>(size).unwrap(),
155 None,
156 false,
157 ComponentCloneBehavior::Default,
158 )
159 };
160
161 (name, size, descriptor)
162 })
163 .map(|(name, size, descriptor)| {
164 let component_id = world.register_component_with_descriptor(descriptor);
165
166 (name, size, component_id)
167 })
168 .collect::<Vec<(&str, usize, ComponentId)>>();
169
170 // Now that our components are registered, let's add them to an entity
171 let mut entity = world.spawn_empty();
172
173 for (_name, size, component_id) in &my_registered_components {
174 // We're just storing some zeroes for the sake of demonstration.
175 let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
176
177 OwningPtr::make(data, |ptr| {
178 // SAFETY:
179 // - ComponentId has been taken from the same world
180 // - Array is created to the layout specified in the world
181 unsafe {
182 entity.insert_by_id(*component_id, ptr);
183 }
184 });
185 }
186
187 for (_name, _size, component_id) in &my_registered_components {
188 // With immutable components, we can read the values...
189 assert!(entity.get_by_id(*component_id).is_ok());
190
191 // ...but we cannot gain a mutable reference.
192 assert!(entity.get_mut_by_id(*component_id).is_err());
193
194 // Instead, you must either remove or replace the value.
195 }
196}
Sourcepub unsafe fn get_mut_assume_mutable_by_id<F>(
&mut self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Mut<'_>, EntityComponentError>where
F: DynamicComponentFetch,
pub unsafe fn get_mut_assume_mutable_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 ComponentId
s.
Assumes the given ComponentId
s refer to mutable components.
You should prefer to use the typed API EntityWorldMut::get_mut_assume_mutable
where
possible and only use this in cases where the actual component types
are not known at compile time.
Unlike EntityWorldMut::get_mut_assume_mutable
, 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. - Returns
EntityComponentError::AliasedMutability
if a component is requested multiple times.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
§Safety
It is the callers responsibility to ensure that
- the provided
ComponentId
s must refer to mutable components.
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 ComponentId
s.
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::MissingComponent
if the entity does not have a component. - Returns
EntityComponentError::AliasedMutability
if a component is requested multiple times.
§Examples
For examples on how to use this method, see EntityMut::get_mut_by_id
.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub unsafe fn into_mut_assume_mutable_by_id<F>(
self,
component_ids: F,
) -> Result<<F as DynamicComponentFetch>::Mut<'w>, EntityComponentError>where
F: DynamicComponentFetch,
pub unsafe fn into_mut_assume_mutable_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 ComponentId
s.
Assumes the given ComponentId
s refer to mutable components.
You should prefer to use the typed API EntityWorldMut::into_mut_assume_mutable
where
possible and only use this in cases where the actual component types
are not known at compile time.
Unlike EntityWorldMut::into_mut_assume_mutable
, 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. - Returns
EntityComponentError::AliasedMutability
if a component is requested multiple times.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
§Safety
It is the callers responsibility to ensure that
- the provided
ComponentId
s must refer to mutable components.
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
31fn demo_1(world: &mut World) {
32 // Immutable components can be inserted just like mutable components.
33 let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
34
35 // But where mutable components can be mutated...
36 let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
37 my_mutable_component.0 = true;
38
39 // ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
40 // is declared as immutable.
41 // let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
42
43 // Instead, you could take or replace the immutable component to update its value.
44 let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
45 my_immutable_component.0 = true;
46 entity.insert(my_immutable_component);
47}
48
49/// This is an example of a component like [`Name`](bevy::prelude::Name), but immutable.
50#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Component, Reflect)]
51#[reflect(Hash, Component)]
52#[component(
53 immutable,
54 // Since this component is immutable, we can fully capture all mutations through
55 // these component hooks. This allows for keeping other parts of the ECS synced
56 // to a component's value at all times.
57 on_insert = on_insert_name,
58 on_replace = on_replace_name,
59)]
60pub struct Name(pub &'static str);
61
62/// This index allows for O(1) lookups of an [`Entity`] by its [`Name`].
63#[derive(Resource, Default)]
64struct NameIndex {
65 name_to_entity: HashMap<Name, Entity>,
66}
67
68impl NameIndex {
69 fn get_entity(&self, name: &'static str) -> Option<Entity> {
70 self.name_to_entity.get(&Name(name)).copied()
71 }
72}
73
74/// When a [`Name`] is inserted, we will add it to our [`NameIndex`].
75///
76/// Since all mutations to [`Name`] are captured by hooks, we know it is not currently
77/// inserted in the index, and its value will not change without triggering a hook.
78fn on_insert_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
79 let Some(&name) = world.entity(entity).get::<Name>() else {
80 unreachable!("OnInsert hook guarantees `Name` is available on entity")
81 };
82 let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
83 return;
84 };
85
86 index.name_to_entity.insert(name, entity);
87}
88
89/// When a [`Name`] is removed or replaced, remove it from our [`NameIndex`].
90///
91/// Since all mutations to [`Name`] are captured by hooks, we know it is currently
92/// inserted in the index.
93fn on_replace_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
94 let Some(&name) = world.entity(entity).get::<Name>() else {
95 unreachable!("OnReplace hook guarantees `Name` is available on entity")
96 };
97 let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
98 return;
99 };
100
101 index.name_to_entity.remove(&name);
102}
103
104fn demo_2(world: &mut World) {
105 // Setup our name index
106 world.init_resource::<NameIndex>();
107
108 // Spawn some entities!
109 let alyssa = world.spawn(Name("Alyssa")).id();
110 let javier = world.spawn(Name("Javier")).id();
111
112 // Check our index
113 let index = world.resource::<NameIndex>();
114
115 assert_eq!(index.get_entity("Alyssa"), Some(alyssa));
116 assert_eq!(index.get_entity("Javier"), Some(javier));
117
118 // Changing the name of an entity is also fully capture by our index
119 world.entity_mut(javier).insert(Name("Steven"));
120
121 // Javier changed their name to Steven
122 let steven = javier;
123
124 // Check our index
125 let index = world.resource::<NameIndex>();
126
127 assert_eq!(index.get_entity("Javier"), None);
128 assert_eq!(index.get_entity("Steven"), Some(steven));
129}
More examples
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}
531 fn display_settings_menu_setup(mut commands: Commands, display_quality: Res<DisplayQuality>) {
532 fn button_node() -> Node {
533 Node {
534 width: Val::Px(200.0),
535 height: Val::Px(65.0),
536 margin: UiRect::all(Val::Px(20.0)),
537 justify_content: JustifyContent::Center,
538 align_items: AlignItems::Center,
539 ..default()
540 }
541 }
542 fn button_text_style() -> impl Bundle {
543 (
544 TextFont {
545 font_size: 33.0,
546 ..default()
547 },
548 TextColor(TEXT_COLOR),
549 )
550 }
551
552 let display_quality = *display_quality;
553 commands.spawn((
554 Node {
555 width: Val::Percent(100.0),
556 height: Val::Percent(100.0),
557 align_items: AlignItems::Center,
558 justify_content: JustifyContent::Center,
559 ..default()
560 },
561 OnDisplaySettingsMenuScreen,
562 children![(
563 Node {
564 flex_direction: FlexDirection::Column,
565 align_items: AlignItems::Center,
566 ..default()
567 },
568 BackgroundColor(CRIMSON.into()),
569 children![
570 // Create a new `Node`, this time not setting its `flex_direction`. It will
571 // use the default value, `FlexDirection::Row`, from left to right.
572 (
573 Node {
574 align_items: AlignItems::Center,
575 ..default()
576 },
577 BackgroundColor(CRIMSON.into()),
578 Children::spawn((
579 // Display a label for the current setting
580 Spawn((Text::new("Display Quality"), button_text_style())),
581 SpawnWith(move |parent: &mut ChildSpawner| {
582 for quality_setting in [
583 DisplayQuality::Low,
584 DisplayQuality::Medium,
585 DisplayQuality::High,
586 ] {
587 let mut entity = parent.spawn((
588 Button,
589 Node {
590 width: Val::Px(150.0),
591 height: Val::Px(65.0),
592 ..button_node()
593 },
594 BackgroundColor(NORMAL_BUTTON),
595 quality_setting,
596 children![(
597 Text::new(format!("{quality_setting:?}")),
598 button_text_style(),
599 )],
600 ));
601 if display_quality == quality_setting {
602 entity.insert(SelectedOption);
603 }
604 }
605 })
606 ))
607 ),
608 // Display the back button to return to the settings screen
609 (
610 Button,
611 button_node(),
612 BackgroundColor(NORMAL_BUTTON),
613 MenuButtonAction::BackToSettings,
614 children![(Text::new("Back"), button_text_style())]
615 )
616 ]
617 )],
618 ));
619 }
620
621 fn sound_settings_menu_setup(mut commands: Commands, volume: Res<Volume>) {
622 let button_node = Node {
623 width: Val::Px(200.0),
624 height: Val::Px(65.0),
625 margin: UiRect::all(Val::Px(20.0)),
626 justify_content: JustifyContent::Center,
627 align_items: AlignItems::Center,
628 ..default()
629 };
630 let button_text_style = (
631 TextFont {
632 font_size: 33.0,
633 ..default()
634 },
635 TextColor(TEXT_COLOR),
636 );
637
638 let volume = *volume;
639 let button_node_clone = button_node.clone();
640 commands.spawn((
641 Node {
642 width: Val::Percent(100.0),
643 height: Val::Percent(100.0),
644 align_items: AlignItems::Center,
645 justify_content: JustifyContent::Center,
646 ..default()
647 },
648 OnSoundSettingsMenuScreen,
649 children![(
650 Node {
651 flex_direction: FlexDirection::Column,
652 align_items: AlignItems::Center,
653 ..default()
654 },
655 BackgroundColor(CRIMSON.into()),
656 children![
657 (
658 Node {
659 align_items: AlignItems::Center,
660 ..default()
661 },
662 BackgroundColor(CRIMSON.into()),
663 Children::spawn((
664 Spawn((Text::new("Volume"), button_text_style.clone())),
665 SpawnWith(move |parent: &mut ChildSpawner| {
666 for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
667 let mut entity = parent.spawn((
668 Button,
669 Node {
670 width: Val::Px(30.0),
671 height: Val::Px(65.0),
672 ..button_node_clone.clone()
673 },
674 BackgroundColor(NORMAL_BUTTON),
675 Volume(volume_setting),
676 ));
677 if volume == Volume(volume_setting) {
678 entity.insert(SelectedOption);
679 }
680 }
681 })
682 ))
683 ),
684 (
685 Button,
686 button_node,
687 BackgroundColor(NORMAL_BUTTON),
688 MenuButtonAction::BackToSettings,
689 children![(Text::new("Back"), button_text_style)]
690 )
691 ]
692 )],
693 ));
694 }
Sourcepub fn insert_with_relationship_hook_mode<T>(
&mut self,
bundle: T,
relationship_hook_mode: RelationshipHookMode,
) -> &mut EntityWorldMut<'w>where
T: Bundle,
pub fn insert_with_relationship_hook_mode<T>(
&mut self,
bundle: T,
relationship_hook_mode: RelationshipHookMode,
) -> &mut EntityWorldMut<'w>where
T: Bundle,
Adds a Bundle
of components to the entity.
Relationship
components in the bundle will follow the configuration
in relationship_hook_mode
.
This will overwrite any previous value(s) of the same component type.
§Warning
This can easily break the integrity of relationships. This is intended to be used for cloning and spawning code internals, not most user-facing scenarios.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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,
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
ComponentId
must be from the same world asEntityWorldMut
OwningPtr
must be a valid reference to the type represented byComponentId
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
136fn demo_3(world: &mut World) {
137 // This is a list of dynamic components we will create.
138 // The first item is the name of the component, and the second is the size
139 // in bytes.
140 let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
141
142 // This pipeline takes our component descriptions, registers them, and gets
143 // their ComponentId's.
144 let my_registered_components = my_dynamic_components
145 .into_iter()
146 .map(|(name, size)| {
147 // SAFETY:
148 // - No drop command is required
149 // - The component will store [u8; size], which is Send + Sync
150 let descriptor = unsafe {
151 ComponentDescriptor::new_with_layout(
152 name.to_string(),
153 StorageType::Table,
154 Layout::array::<u8>(size).unwrap(),
155 None,
156 false,
157 ComponentCloneBehavior::Default,
158 )
159 };
160
161 (name, size, descriptor)
162 })
163 .map(|(name, size, descriptor)| {
164 let component_id = world.register_component_with_descriptor(descriptor);
165
166 (name, size, component_id)
167 })
168 .collect::<Vec<(&str, usize, ComponentId)>>();
169
170 // Now that our components are registered, let's add them to an entity
171 let mut entity = world.spawn_empty();
172
173 for (_name, size, component_id) in &my_registered_components {
174 // We're just storing some zeroes for the sake of demonstration.
175 let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
176
177 OwningPtr::make(data, |ptr| {
178 // SAFETY:
179 // - ComponentId has been taken from the same world
180 // - Array is created to the layout specified in the world
181 unsafe {
182 entity.insert_by_id(*component_id, ptr);
183 }
184 });
185 }
186
187 for (_name, _size, component_id) in &my_registered_components {
188 // With immutable components, we can read the values...
189 assert!(entity.get_by_id(*component_id).is_ok());
190
191 // ...but we cannot gain a mutable reference.
192 assert!(entity.get_mut_by_id(*component_id).is_err());
193
194 // Instead, you must either remove or replace the value.
195 }
196}
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
ComponentId
must be from the same world asEntityWorldMut
- Each
OwningPtr
must be a valid reference to the type represented byComponentId
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
79fn stress_test(num_entities: u32, num_components: u32, num_systems: u32) {
80 let mut rng = ChaCha8Rng::seed_from_u64(42);
81 let mut app = App::default();
82 let world = app.world_mut();
83
84 // register a bunch of components
85 let component_ids: Vec<ComponentId> = (1..=num_components)
86 .map(|i| {
87 world.register_component_with_descriptor(
88 // SAFETY:
89 // * We don't implement a drop function
90 // * u8 is Sync and Send
91 unsafe {
92 ComponentDescriptor::new_with_layout(
93 format!("Component{}", i).to_string(),
94 StorageType::Table,
95 Layout::new::<u8>(),
96 None,
97 true, // is mutable
98 ComponentCloneBehavior::Default,
99 )
100 },
101 )
102 })
103 .collect();
104
105 // fill the schedule with systems
106 let mut schedule = Schedule::new(Update);
107 for _ in 1..=num_systems {
108 let num_access_components = rng.gen_range(1..10);
109 let access_components: Vec<ComponentId> = component_ids
110 .choose_multiple(&mut rng, num_access_components)
111 .copied()
112 .collect();
113 let system = (QueryParamBuilder::new(|builder| {
114 for &access_component in &access_components {
115 if rand::random::<bool>() {
116 builder.mut_id(access_component);
117 } else {
118 builder.ref_id(access_component);
119 }
120 }
121 }),)
122 .build_state(world)
123 .build_any_system(base_system);
124 schedule.add_systems((move || access_components.clone()).pipe(system));
125 }
126
127 // spawn a bunch of entities
128 for _ in 1..=num_entities {
129 let num_components = rng.gen_range(1..10);
130 let components: Vec<ComponentId> = component_ids
131 .choose_multiple(&mut rng, num_components)
132 .copied()
133 .collect();
134
135 let mut entity = world.spawn_empty();
136 // We use `ManuallyDrop` here as we need to avoid dropping the u8's when `values` is dropped
137 // since ownership of the values is passed to the world in `insert_by_ids`.
138 // But we do want to deallocate the memory when values is dropped.
139 let mut values: Vec<ManuallyDrop<u8>> = components
140 .iter()
141 .map(|_id| ManuallyDrop::new(rng.gen_range(0..255)))
142 .collect();
143 let ptrs: Vec<OwningPtr> = values
144 .iter_mut()
145 .map(|value| {
146 // SAFETY:
147 // * We don't read/write `values` binding after this and values are `ManuallyDrop`,
148 // so we have the right to drop/move the values
149 unsafe { PtrMut::from(value).promote() }
150 })
151 .collect();
152 // SAFETY:
153 // * component_id's are from the same world
154 // * `values` was initialized above, so references are valid
155 unsafe {
156 entity.insert_by_ids(&components, ptrs.into_iter());
157 }
158 }
159
160 println!(
161 "Number of Archetype-Components: {}",
162 world.archetypes().archetype_components_len()
163 );
164
165 // overwrite Update schedule in the app
166 app.add_schedule(schedule);
167 app.add_plugins(MinimalPlugins)
168 .add_plugins(DiagnosticsPlugin)
169 .add_plugins(LogPlugin::default())
170 .add_plugins(FrameTimeDiagnosticsPlugin::default())
171 .add_plugins(LogDiagnosticsPlugin::filtered(vec![DiagnosticPath::new(
172 "fps",
173 )]));
174 app.run();
175}
More examples
51fn main() {
52 let mut world = World::new();
53 let mut lines = std::io::stdin().lines();
54 let mut component_names = HashMap::<String, ComponentId>::new();
55 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57 println!("{PROMPT}");
58 loop {
59 print!("\n> ");
60 let _ = std::io::stdout().flush();
61 let Some(Ok(line)) = lines.next() else {
62 return;
63 };
64
65 if line.is_empty() {
66 return;
67 };
68
69 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70 match &line.chars().next() {
71 Some('c') => println!("{COMPONENT_PROMPT}"),
72 Some('s') => println!("{ENTITY_PROMPT}"),
73 Some('q') => println!("{QUERY_PROMPT}"),
74 _ => println!("{PROMPT}"),
75 }
76 continue;
77 };
78
79 match &first[0..1] {
80 "c" => {
81 rest.split(',').for_each(|component| {
82 let mut component = component.split_whitespace();
83 let Some(name) = component.next() else {
84 return;
85 };
86 let size = match component.next().map(str::parse) {
87 Some(Ok(size)) => size,
88 _ => 0,
89 };
90 // Register our new component to the world with a layout specified by it's size
91 // SAFETY: [u64] is Send + Sync
92 let id = world.register_component_with_descriptor(unsafe {
93 ComponentDescriptor::new_with_layout(
94 name.to_string(),
95 StorageType::Table,
96 Layout::array::<u64>(size).unwrap(),
97 None,
98 true,
99 ComponentCloneBehavior::Default,
100 )
101 });
102 let Some(info) = world.components().get_info(id) else {
103 return;
104 };
105 component_names.insert(name.to_string(), id);
106 component_info.insert(id, info.clone());
107 println!("Component {} created with id: {}", name, id.index());
108 });
109 }
110 "s" => {
111 let mut to_insert_ids = Vec::new();
112 let mut to_insert_data = Vec::new();
113 rest.split(',').for_each(|component| {
114 let mut component = component.split_whitespace();
115 let Some(name) = component.next() else {
116 return;
117 };
118
119 // Get the id for the component with the given name
120 let Some(&id) = component_names.get(name) else {
121 println!("Component {name} does not exist");
122 return;
123 };
124
125 // Calculate the length for the array based on the layout created for this component id
126 let info = world.components().get_info(id).unwrap();
127 let len = info.layout().size() / size_of::<u64>();
128 let mut values: Vec<u64> = component
129 .take(len)
130 .filter_map(|value| value.parse::<u64>().ok())
131 .collect();
132 values.resize(len, 0);
133
134 // Collect the id and array to be inserted onto our entity
135 to_insert_ids.push(id);
136 to_insert_data.push(values);
137 });
138
139 let mut entity = world.spawn_empty();
140
141 // Construct an `OwningPtr` for each component in `to_insert_data`
142 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144 // SAFETY:
145 // - Component ids have been taken from the same world
146 // - Each array is created to the layout specified in the world
147 unsafe {
148 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149 }
150
151 println!("Entity spawned with id: {}", entity.id());
152 }
153 "q" => {
154 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155 parse_query(rest, &mut builder, &component_names);
156 let mut query = builder.build();
157 query.iter_mut(&mut world).for_each(|filtered_entity| {
158 let terms = filtered_entity
159 .access()
160 .try_iter_component_access()
161 .unwrap()
162 .map(|component_access| {
163 let id = *component_access.index();
164 let ptr = filtered_entity.get_by_id(id).unwrap();
165 let info = component_info.get(&id).unwrap();
166 let len = info.layout().size() / size_of::<u64>();
167
168 // SAFETY:
169 // - All components are created with layout [u64]
170 // - len is calculated from the component descriptor
171 let data = unsafe {
172 std::slice::from_raw_parts_mut(
173 ptr.assert_unique().as_ptr().cast::<u64>(),
174 len,
175 )
176 };
177
178 // If we have write access, increment each value once
179 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180 data.iter_mut().for_each(|data| {
181 *data += 1;
182 });
183 }
184
185 format!("{}: {:?}", info.name(), data[0..len].to_vec())
186 })
187 .collect::<Vec<_>>()
188 .join(", ");
189
190 println!("{}: {}", filtered_entity.id(), terms);
191 });
192 }
193 _ => continue,
194 }
195 }
196}
Sourcepub fn take<T>(&mut self) -> Option<T>where
T: Bundle + BundleFromComponents,
pub fn take<T>(&mut self) -> Option<T>where
T: Bundle + BundleFromComponents,
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Examples found in repository?
31fn demo_1(world: &mut World) {
32 // Immutable components can be inserted just like mutable components.
33 let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
34
35 // But where mutable components can be mutated...
36 let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
37 my_mutable_component.0 = true;
38
39 // ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
40 // is declared as immutable.
41 // let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
42
43 // Instead, you could take or replace the immutable component to update its value.
44 let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
45 my_immutable_component.0 = true;
46 entity.insert(my_immutable_component);
47}
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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,
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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
or if the
entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn remove_by_ids(
&mut self,
component_ids: &[ComponentId],
) -> &mut EntityWorldMut<'w>
pub fn remove_by_ids( &mut self, component_ids: &[ComponentId], ) -> &mut EntityWorldMut<'w>
Removes a dynamic bundle from the entity if it exists.
You should prefer to use the typed API EntityWorldMut::remove
where possible.
§Panics
Panics if any of the provided ComponentId
s do not exist in the World
or if the
entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn clear(&mut self) -> &mut EntityWorldMut<'w>
pub fn clear(&mut self) -> &mut EntityWorldMut<'w>
Removes all components associated with the entity.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn despawn(self)
pub fn despawn(self)
Despawns the current entity.
See World::despawn
for more details.
§Note
This will also despawn any Children
entities, and any other RelationshipTarget
that is configured
to despawn descendants. This results in “recursive despawn” behavior.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn despawn_recursive(self)
👎Deprecated since 0.16.0: Use entity.despawn(), which now automatically despawns recursively.
pub fn despawn_recursive(self)
Despawns the provided entity and its descendants.
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 is_despawned(&self) -> bool
pub fn is_despawned(&self) -> bool
Returns if the entity has been despawned.
Normally it shouldn’t be needed to explicitly check if the entity has been despawned
between commands as this shouldn’t happen. However, for some special cases where it
is known that a hook or an observer might despawn the entity while a EntityWorldMut
reference is still held, this method can be used to check if the entity is still alive
to avoid panicking when calling further methods.
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).unwrap().0, 4);
entity.entry::<Comp>().and_modify(|mut c| c.0 += 1);
assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 5);
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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.
§Panics
If the entity has been despawned while this EntityWorldMut
is still alive.
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>
Sourcepub fn clone_with(
&mut self,
target: Entity,
config: impl FnOnce(&mut EntityClonerBuilder<'_>) + Send + Sync + 'static,
) -> &mut EntityWorldMut<'w>
pub fn clone_with( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_>) + Send + Sync + 'static, ) -> &mut EntityWorldMut<'w>
Clones parts of an entity (components, observers, etc.) onto another entity,
configured through EntityClonerBuilder
.
By default, the other entity will receive all the components of the original that implement
Clone
or Reflect
.
Configure through EntityClonerBuilder
as follows:
world.entity_mut(entity).clone_with(target, |builder| {
builder.deny::<ComponentB>();
});
See EntityClonerBuilder
for more options.
§Panics
- If this entity has been despawned while this
EntityWorldMut
is still alive. - If the target entity does not exist.
Sourcepub fn clone_and_spawn(&mut self) -> Entity
pub fn clone_and_spawn(&mut self) -> Entity
Spawns a clone of this entity and returns the Entity
of the clone.
The clone will receive all the components of the original that implement
Clone
or Reflect
.
To configure cloning behavior (such as only cloning certain components),
use EntityWorldMut::clone_and_spawn_with
.
§Panics
If this entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn clone_and_spawn_with(
&mut self,
config: impl FnOnce(&mut EntityClonerBuilder<'_>) + Send + Sync + 'static,
) -> Entity
pub fn clone_and_spawn_with( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_>) + Send + Sync + 'static, ) -> Entity
Spawns a clone of this entity and allows configuring cloning behavior
using EntityClonerBuilder
, returning the Entity
of the clone.
By default, the clone will receive all the components of the original that implement
Clone
or Reflect
.
Configure through EntityClonerBuilder
as follows:
let entity_clone = world.entity_mut(entity).clone_and_spawn_with(|builder| {
builder.deny::<ComponentB>();
});
See EntityClonerBuilder
for more options.
§Panics
If this entity has been despawned while this EntityWorldMut
is still alive.
Sourcepub fn clone_components<B>(&mut self, target: Entity) -> &mut EntityWorldMut<'w>where
B: Bundle,
pub fn clone_components<B>(&mut self, target: Entity) -> &mut EntityWorldMut<'w>where
B: Bundle,
Sourcepub fn move_components<B>(&mut self, target: Entity) -> &mut EntityWorldMut<'w>where
B: Bundle,
pub fn move_components<B>(&mut self, target: Entity) -> &mut EntityWorldMut<'w>where
B: Bundle,
Clones the specified components of this entity and inserts them into another entity, then removes the components from this entity.
Components can only be cloned if they implement
Clone
or Reflect
.
§Panics
- If this entity has been despawned while this
EntityWorldMut
is still alive. - If the target entity does not exist.
Sourcepub fn spawned_by(&self) -> MaybeLocation
pub fn spawned_by(&self) -> MaybeLocation
Returns the source code location from which this entity has last been spawned.
Trait Implementations§
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<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a>
impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a>
Source§fn from(entity: &'a EntityWorldMut<'_>) -> EntityRef<'a>
fn from(entity: &'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(entity: &'a mut EntityWorldMut<'_>) -> EntityMut<'a>
fn from(entity: &'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(entity: EntityWorldMut<'w>) -> EntityMut<'w>
fn from(entity: 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: EntityWorldMut<'w>) -> EntityRef<'w>
fn from(entity: 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>
, which can then be
downcast
into Box<dyn 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>
, which 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> 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> DowncastSend for T
impl<T> DowncastSend for T
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.