EntityWorldMut

Struct EntityWorldMut 

Source
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>

Source

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.

Source

pub fn add_children(&mut self, children: &[Entity]) -> &mut EntityWorldMut<'w>

Adds the given children to this entity See also add_related.

Source

pub fn clear_children(&mut self) -> &mut EntityWorldMut<'w>

Removes all the children from this entity. See also clear_related

Source

pub fn insert_children( &mut self, index: usize, children: &[Entity], ) -> &mut EntityWorldMut<'w>

Insert children at specific index. See also insert_related.

Source

pub fn insert_child( &mut self, index: usize, child: Entity, ) -> &mut EntityWorldMut<'w>

Insert child at specific index. See also insert_related.

Source

pub fn add_child(&mut self, child: Entity) -> &mut EntityWorldMut<'w>

Adds the given child to this entity See also add_related.

Source

pub fn remove_children( &mut self, children: &[Entity], ) -> &mut EntityWorldMut<'w>

Removes the relationship between this entity and the given entities.

Source

pub fn remove_child(&mut self, child: Entity) -> &mut EntityWorldMut<'w>

Removes the relationship between this entity and the given entity.

Source

pub fn replace_children( &mut self, children: &[Entity], ) -> &mut EntityWorldMut<'w>

Replaces all the related children with a new set of children.

Source

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 broken and the command is executed.

Source

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.

Source§

impl<'w> EntityWorldMut<'w>

Source

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
§Note

Prefer to use the typed EntityWorldMut::insert if possible. Adding a reflected component is much slower.

Source

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 given Component or Bundle.
  • If the component or bundle data is invalid. See PartialReflect::apply for further details.
  • If the given Resource is not present in the World.
Source

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 path 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 the World.
§Note

Prefer to use the typed EntityCommands::remove if possible. Removing a reflected component is much slower.

Source

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 the World.
Source§

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.

Removes the relation R between this entity and all its related entities.

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 in entities_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 in entities_to_unrelate) plus the newly related entities.
  • newly_related_entities: A subset of entities_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.

Source

pub fn despawn_children(&mut self) -> &mut EntityWorldMut<'w>

Despawns the children of this entity. This entity will not be despawned.

This is a specialization of despawn_related, a more general method for despawning via relationships.

Source

pub fn insert_recursive<S>( &mut self, bundle: impl Bundle + Clone, ) -> &mut EntityWorldMut<'w>

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.

Source

pub fn remove_recursive<S, B>(&mut self) -> &mut EntityWorldMut<'w>

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>

Source

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.

Source

pub fn as_readonly(&self) -> EntityRef<'_>

Gets read-only access to all of the entity’s components.

Source

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.

Source

pub fn as_mutable(&mut self) -> EntityMut<'_>

Gets non-structural mutable access to all of the entity’s components.

Source

pub fn id(&self) -> Entity

Returns the ID of the current entity.

Examples found in repository?
examples/ecs/immutable_components.rs (line 108)
103fn demo_2(world: &mut World) {
104    // Setup our name index
105    world.init_resource::<NameIndex>();
106
107    // Spawn some entities!
108    let alyssa = world.spawn(Name("Alyssa")).id();
109    let javier = world.spawn(Name("Javier")).id();
110
111    // Check our index
112    let index = world.resource::<NameIndex>();
113
114    assert_eq!(index.get_entity("Alyssa"), Some(alyssa));
115    assert_eq!(index.get_entity("Javier"), Some(javier));
116
117    // Changing the name of an entity is also fully capture by our index
118    world.entity_mut(javier).insert(Name("Steven"));
119
120    // Javier changed their name to Steven
121    let steven = javier;
122
123    // Check our index
124    let index = world.resource::<NameIndex>();
125
126    assert_eq!(index.get_entity("Javier"), None);
127    assert_eq!(index.get_entity("Steven"), Some(steven));
128}
More examples
Hide additional examples
examples/ui/scrollbars.rs (line 105)
61fn scroll_area_demo() -> impl Bundle {
62    (
63        // Frame element which contains the scroll area and scrollbars.
64        Node {
65            display: Display::Grid,
66            width: px(200),
67            height: px(150),
68            grid_template_columns: vec![RepeatedGridTrack::flex(1, 1.), RepeatedGridTrack::auto(1)],
69            grid_template_rows: vec![RepeatedGridTrack::flex(1, 1.), RepeatedGridTrack::auto(1)],
70            row_gap: px(2),
71            column_gap: px(2),
72            ..default()
73        },
74        Children::spawn((SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| {
75            // The actual scrolling area.
76            // Note that we're using `SpawnWith` here because we need to get the entity id of the
77            // scroll area in order to set the target of the scrollbars.
78            let scroll_area_id = parent
79                .spawn((
80                    Node {
81                        display: Display::Flex,
82                        flex_direction: FlexDirection::Column,
83                        padding: UiRect::all(px(4)),
84                        overflow: Overflow::scroll(),
85                        ..default()
86                    },
87                    BackgroundColor(colors::GRAY1.into()),
88                    ScrollPosition(Vec2::new(0.0, 10.0)),
89                    Children::spawn((
90                        // The actual content of the scrolling area
91                        Spawn(text_row("Alpha Wolf")),
92                        Spawn(text_row("Beta Blocker")),
93                        Spawn(text_row("Delta Sleep")),
94                        Spawn(text_row("Gamma Ray")),
95                        Spawn(text_row("Epsilon Eridani")),
96                        Spawn(text_row("Zeta Function")),
97                        Spawn(text_row("Lambda Calculus")),
98                        Spawn(text_row("Nu Metal")),
99                        Spawn(text_row("Pi Day")),
100                        Spawn(text_row("Chi Pants")),
101                        Spawn(text_row("Psi Powers")),
102                        Spawn(text_row("Omega Fatty Acid")),
103                    )),
104                ))
105                .id();
106
107            // Vertical scrollbar
108            parent.spawn((
109                Node {
110                    min_width: px(8),
111                    grid_row: GridPlacement::start(1),
112                    grid_column: GridPlacement::start(2),
113                    ..default()
114                },
115                Scrollbar {
116                    orientation: ControlOrientation::Vertical,
117                    target: scroll_area_id,
118                    min_thumb_length: 8.0,
119                },
120                Children::spawn(Spawn((
121                    Node {
122                        position_type: PositionType::Absolute,
123                        ..default()
124                    },
125                    Hovered::default(),
126                    BackgroundColor(colors::GRAY2.into()),
127                    BorderRadius::all(px(4)),
128                    CoreScrollbarThumb,
129                ))),
130            ));
131
132            // Horizontal scrollbar
133            parent.spawn((
134                Node {
135                    min_height: px(8),
136                    grid_row: GridPlacement::start(2),
137                    grid_column: GridPlacement::start(1),
138                    ..default()
139                },
140                Scrollbar {
141                    orientation: ControlOrientation::Horizontal,
142                    target: scroll_area_id,
143                    min_thumb_length: 8.0,
144                },
145                Children::spawn(Spawn((
146                    Node {
147                        position_type: PositionType::Absolute,
148                        ..default()
149                    },
150                    Hovered::default(),
151                    BackgroundColor(colors::GRAY2.into()),
152                    BorderRadius::all(px(4)),
153                    CoreScrollbarThumb,
154                ))),
155            ));
156        }),)),
157    )
158}
examples/ecs/dynamic.rs (line 151)
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}
Source

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.

Source

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.

Source

pub fn contains<T>(&self) -> bool
where 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.

Source

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
§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Source

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
§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Source

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.

Source

pub fn components<Q>(&self) -> <Q as QueryData>::Item<'_, 'static>

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.

Source

pub fn get_components<Q>(&self) -> Option<<Q as QueryData>::Item<'_, 'static>>

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.

Source

pub unsafe fn get_components_mut_unchecked<Q>( &mut self, ) -> Option<<Q as QueryData>::Item<'_, 'static>>

Returns 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.

§Example
#[derive(Component)]
struct X(usize);
#[derive(Component)]
struct Y(usize);

let mut entity = world.spawn((X(0), Y(0)));
// Get mutable access to two components at once
// SAFETY: X and Y are different components
let (mut x, mut y) =
    unsafe { entity.get_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
*x = X(1);
*y = Y(1);
// This would trigger undefined behavior, as the `&mut X`s would alias:
// entity.get_components_mut_unchecked::<(&mut X, &mut X)>();
§Safety

It is the caller’s responsibility to ensure that the QueryData does not provide aliasing mutable references to the same component.

Source

pub unsafe fn into_components_mut_unchecked<Q>( self, ) -> Option<<Q as QueryData>::Item<'w, 'static>>

Consumes self and returns components for the current entity that match the query Q for the world lifetime 'w, or None if the entity does not have the components required by the query Q.

§Example
#[derive(Component)]
struct X(usize);
#[derive(Component)]
struct Y(usize);

let mut entity = world.spawn((X(0), Y(0)));
// Get mutable access to two components at once
// SAFETY: X and Y are different components
let (mut x, mut y) =
    unsafe { entity.into_components_mut_unchecked::<(&mut X, &mut Y)>() }.unwrap();
*x = X(1);
*y = Y(1);
// This would trigger undefined behavior, as the `&mut X`s would alias:
// entity.into_components_mut_unchecked::<(&mut X, &mut X)>();
§Safety

It is the caller’s responsibility to ensure that the QueryData does not provide aliasing mutable references to the same component.

Source

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.

Source

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.

§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Source

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.

Source

pub fn get_mut<T>(&mut self) -> Option<Mut<'_, T>>
where T: Component<Mutability = Mutable>,

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?
examples/ecs/immutable_components.rs (line 35)
30fn demo_1(world: &mut World) {
31    // Immutable components can be inserted just like mutable components.
32    let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
33
34    // But where mutable components can be mutated...
35    let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
36    my_mutable_component.0 = true;
37
38    // ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
39    // is declared as immutable.
40    // let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
41
42    // Instead, you could take or replace the immutable component to update its value.
43    let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
44    my_immutable_component.0 = true;
45    entity.insert(my_immutable_component);
46}
Source

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 Remove and Replace 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.

Source

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 Remove and Replace 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.

Source

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
Source

pub fn into_mut<T>(self) -> Option<Mut<'w, T>>
where T: Component<Mutability = Mutable>,

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.

Source

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
Source

pub fn resource<R>(&self) -> &R
where R: Resource,

Gets a reference to the resource of the given type

§Panics

Panics if the resource does not exist. Use get_resource instead if you want to handle this case.

Source

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.

Source

pub fn get_resource<R>(&self) -> Option<&R>
where R: Resource,

Gets a reference to the resource of the given type if it exists

Source

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

Source

pub fn resource_scope<R, U>( &mut self, f: impl FnOnce(&mut EntityWorldMut<'_>, Mut<'_, R>) -> U, ) -> U
where R: Resource,

Temporarily removes the requested resource from the World, runs custom user code, then re-adds the resource before returning.

§Panics

Panics if the resource does not exist. Use try_resource_scope instead if you want to handle this case.

See World::resource_scope for further details.

Source

pub fn try_resource_scope<R, U>( &mut self, f: impl FnOnce(&mut EntityWorldMut<'_>, Mut<'_, R>) -> U, ) -> Option<U>
where R: Resource,

Temporarily removes the requested resource from the World if it exists, runs custom user code, then re-adds the resource before returning. Returns None if the resource does not exist in the World.

See World::try_resource_scope for further details.

Source

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.

Source

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.

Source

pub fn get_by_id<F>( &self, component_ids: F, ) -> Result<<F as DynamicComponentFetch>::Ref<'_>, EntityComponentError>

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.

§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Examples found in repository?
examples/ecs/immutable_components.rs (line 188)
135fn demo_3(world: &mut World) {
136    // This is a list of dynamic components we will create.
137    // The first item is the name of the component, and the second is the size
138    // in bytes.
139    let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
140
141    // This pipeline takes our component descriptions, registers them, and gets
142    // their ComponentId's.
143    let my_registered_components = my_dynamic_components
144        .into_iter()
145        .map(|(name, size)| {
146            // SAFETY:
147            // - No drop command is required
148            // - The component will store [u8; size], which is Send + Sync
149            let descriptor = unsafe {
150                ComponentDescriptor::new_with_layout(
151                    name.to_string(),
152                    StorageType::Table,
153                    Layout::array::<u8>(size).unwrap(),
154                    None,
155                    false,
156                    ComponentCloneBehavior::Default,
157                )
158            };
159
160            (name, size, descriptor)
161        })
162        .map(|(name, size, descriptor)| {
163            let component_id = world.register_component_with_descriptor(descriptor);
164
165            (name, size, component_id)
166        })
167        .collect::<Vec<(&str, usize, ComponentId)>>();
168
169    // Now that our components are registered, let's add them to an entity
170    let mut entity = world.spawn_empty();
171
172    for (_name, size, component_id) in &my_registered_components {
173        // We're just storing some zeroes for the sake of demonstration.
174        let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
175
176        OwningPtr::make(data, |ptr| {
177            // SAFETY:
178            // - ComponentId has been taken from the same world
179            // - Array is created to the layout specified in the world
180            unsafe {
181                entity.insert_by_id(*component_id, ptr);
182            }
183        });
184    }
185
186    for (_name, _size, component_id) in &my_registered_components {
187        // With immutable components, we can read the values...
188        assert!(entity.get_by_id(*component_id).is_ok());
189
190        // ...but we cannot gain a mutable reference.
191        assert!(entity.get_mut_by_id(*component_id).is_err());
192
193        // Instead, you must either remove or replace the value.
194    }
195}
Source

pub fn into_borrow_by_id<F>( self, component_ids: F, ) -> Result<<F as DynamicComponentFetch>::Ref<'w>, EntityComponentError>

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.

§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Source

pub fn get_mut_by_id<F>( &mut self, component_ids: F, ) -> Result<<F as DynamicComponentFetch>::Mut<'_>, EntityComponentError>

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
§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?
examples/ecs/immutable_components.rs (line 191)
135fn demo_3(world: &mut World) {
136    // This is a list of dynamic components we will create.
137    // The first item is the name of the component, and the second is the size
138    // in bytes.
139    let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
140
141    // This pipeline takes our component descriptions, registers them, and gets
142    // their ComponentId's.
143    let my_registered_components = my_dynamic_components
144        .into_iter()
145        .map(|(name, size)| {
146            // SAFETY:
147            // - No drop command is required
148            // - The component will store [u8; size], which is Send + Sync
149            let descriptor = unsafe {
150                ComponentDescriptor::new_with_layout(
151                    name.to_string(),
152                    StorageType::Table,
153                    Layout::array::<u8>(size).unwrap(),
154                    None,
155                    false,
156                    ComponentCloneBehavior::Default,
157                )
158            };
159
160            (name, size, descriptor)
161        })
162        .map(|(name, size, descriptor)| {
163            let component_id = world.register_component_with_descriptor(descriptor);
164
165            (name, size, component_id)
166        })
167        .collect::<Vec<(&str, usize, ComponentId)>>();
168
169    // Now that our components are registered, let's add them to an entity
170    let mut entity = world.spawn_empty();
171
172    for (_name, size, component_id) in &my_registered_components {
173        // We're just storing some zeroes for the sake of demonstration.
174        let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
175
176        OwningPtr::make(data, |ptr| {
177            // SAFETY:
178            // - ComponentId has been taken from the same world
179            // - Array is created to the layout specified in the world
180            unsafe {
181                entity.insert_by_id(*component_id, ptr);
182            }
183        });
184    }
185
186    for (_name, _size, component_id) in &my_registered_components {
187        // With immutable components, we can read the values...
188        assert!(entity.get_by_id(*component_id).is_ok());
189
190        // ...but we cannot gain a mutable reference.
191        assert!(entity.get_mut_by_id(*component_id).is_err());
192
193        // Instead, you must either remove or replace the value.
194    }
195}
Source

pub unsafe fn get_mut_assume_mutable_by_id<F>( &mut self, component_ids: F, ) -> Result<<F as DynamicComponentFetch>::Mut<'_>, EntityComponentError>

Returns untyped mutable reference(s) to component(s) for the current entity, based on the given ComponentIds. Assumes the given ComponentIds 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
§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

§Safety

It is the callers responsibility to ensure that

  • the provided ComponentIds must refer to mutable components.
Source

pub fn into_mut_by_id<F>( self, component_ids: F, ) -> Result<<F as DynamicComponentFetch>::Mut<'w>, EntityComponentError>

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
§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.

Source

pub unsafe fn into_mut_assume_mutable_by_id<F>( self, component_ids: F, ) -> Result<<F as DynamicComponentFetch>::Mut<'w>, EntityComponentError>

Consumes self and returns untyped mutable reference(s) to component(s) with lifetime 'w for the current entity, based on the given ComponentIds. Assumes the given ComponentIds 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
§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

§Safety

It is the callers responsibility to ensure that

  • the provided ComponentIds must refer to mutable components.
Source

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?
examples/ecs/immutable_components.rs (line 45)
30fn demo_1(world: &mut World) {
31    // Immutable components can be inserted just like mutable components.
32    let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
33
34    // But where mutable components can be mutated...
35    let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
36    my_mutable_component.0 = true;
37
38    // ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
39    // is declared as immutable.
40    // let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
41
42    // Instead, you could take or replace the immutable component to update its value.
43    let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
44    my_immutable_component.0 = true;
45    entity.insert(my_immutable_component);
46}
47
48/// This is an example of a component like [`Name`](bevy::prelude::Name), but immutable.
49#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Component, Reflect)]
50#[reflect(Hash, Component)]
51#[component(
52    immutable,
53    // Since this component is immutable, we can fully capture all mutations through
54    // these component hooks. This allows for keeping other parts of the ECS synced
55    // to a component's value at all times.
56    on_insert = on_insert_name,
57    on_replace = on_replace_name,
58)]
59pub struct Name(pub &'static str);
60
61/// This index allows for O(1) lookups of an [`Entity`] by its [`Name`].
62#[derive(Resource, Default)]
63struct NameIndex {
64    name_to_entity: HashMap<Name, Entity>,
65}
66
67impl NameIndex {
68    fn get_entity(&self, name: &'static str) -> Option<Entity> {
69        self.name_to_entity.get(&Name(name)).copied()
70    }
71}
72
73/// When a [`Name`] is inserted, we will add it to our [`NameIndex`].
74///
75/// Since all mutations to [`Name`] are captured by hooks, we know it is not currently
76/// inserted in the index, and its value will not change without triggering a hook.
77fn on_insert_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
78    let Some(&name) = world.entity(entity).get::<Name>() else {
79        unreachable!("Insert hook guarantees `Name` is available on entity")
80    };
81    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
82        return;
83    };
84
85    index.name_to_entity.insert(name, entity);
86}
87
88/// When a [`Name`] is removed or replaced, remove it from our [`NameIndex`].
89///
90/// Since all mutations to [`Name`] are captured by hooks, we know it is currently
91/// inserted in the index.
92fn on_replace_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
93    let Some(&name) = world.entity(entity).get::<Name>() else {
94        unreachable!("Replace hook guarantees `Name` is available on entity")
95    };
96    let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
97        return;
98    };
99
100    index.name_to_entity.remove(&name);
101}
102
103fn demo_2(world: &mut World) {
104    // Setup our name index
105    world.init_resource::<NameIndex>();
106
107    // Spawn some entities!
108    let alyssa = world.spawn(Name("Alyssa")).id();
109    let javier = world.spawn(Name("Javier")).id();
110
111    // Check our index
112    let index = world.resource::<NameIndex>();
113
114    assert_eq!(index.get_entity("Alyssa"), Some(alyssa));
115    assert_eq!(index.get_entity("Javier"), Some(javier));
116
117    // Changing the name of an entity is also fully capture by our index
118    world.entity_mut(javier).insert(Name("Steven"));
119
120    // Javier changed their name to Steven
121    let steven = javier;
122
123    // Check our index
124    let index = world.resource::<NameIndex>();
125
126    assert_eq!(index.get_entity("Javier"), None);
127    assert_eq!(index.get_entity("Steven"), Some(steven));
128}
More examples
Hide additional examples
examples/async_tasks/async_compute.rs (lines 89-93)
53fn spawn_tasks(mut commands: Commands) {
54    let thread_pool = AsyncComputeTaskPool::get();
55    for x in 0..NUM_CUBES {
56        for y in 0..NUM_CUBES {
57            for z in 0..NUM_CUBES {
58                // Spawn new task on the AsyncComputeTaskPool; the task will be
59                // executed in the background, and the Task future returned by
60                // spawn() can be used to poll for the result
61                let entity = commands.spawn_empty().id();
62                let task = thread_pool.spawn(async move {
63                    let duration = Duration::from_secs_f32(rand::rng().random_range(0.05..5.0));
64
65                    // Pretend this is a time-intensive function. :)
66                    Delay::new(duration).await;
67
68                    // Such hard work, all done!
69                    let transform = Transform::from_xyz(x as f32, y as f32, z as f32);
70                    let mut command_queue = CommandQueue::default();
71
72                    // we use a raw command queue to pass a FnOnce(&mut World) back to be
73                    // applied in a deferred manner.
74                    command_queue.push(move |world: &mut World| {
75                        let (box_mesh_handle, box_material_handle) = {
76                            let mut system_state = SystemState::<(
77                                Res<BoxMeshHandle>,
78                                Res<BoxMaterialHandle>,
79                            )>::new(world);
80                            let (box_mesh_handle, box_material_handle) =
81                                system_state.get_mut(world);
82
83                            (box_mesh_handle.clone(), box_material_handle.clone())
84                        };
85
86                        world
87                            .entity_mut(entity)
88                            // Add our new `Mesh3d` and `MeshMaterial3d` to our tagged entity
89                            .insert((
90                                Mesh3d(box_mesh_handle),
91                                MeshMaterial3d(box_material_handle),
92                                transform,
93                            ));
94                    });
95
96                    command_queue
97                });
98
99                // Add our new task as a component
100                commands.entity(entity).insert(ComputeTransform(task));
101            }
102        }
103    }
104}
examples/games/game_menu.rs (line 591)
519    fn display_settings_menu_setup(mut commands: Commands, display_quality: Res<DisplayQuality>) {
520        fn button_node() -> Node {
521            Node {
522                width: px(200),
523                height: px(65),
524                margin: UiRect::all(px(20)),
525                justify_content: JustifyContent::Center,
526                align_items: AlignItems::Center,
527                ..default()
528            }
529        }
530        fn button_text_style() -> impl Bundle {
531            (
532                TextFont {
533                    font_size: 33.0,
534                    ..default()
535                },
536                TextColor(TEXT_COLOR),
537            )
538        }
539
540        let display_quality = *display_quality;
541        commands.spawn((
542            DespawnOnExit(MenuState::SettingsDisplay),
543            Node {
544                width: percent(100),
545                height: percent(100),
546                align_items: AlignItems::Center,
547                justify_content: JustifyContent::Center,
548                ..default()
549            },
550            OnDisplaySettingsMenuScreen,
551            children![(
552                Node {
553                    flex_direction: FlexDirection::Column,
554                    align_items: AlignItems::Center,
555                    ..default()
556                },
557                BackgroundColor(CRIMSON.into()),
558                children![
559                    // Create a new `Node`, this time not setting its `flex_direction`. It will
560                    // use the default value, `FlexDirection::Row`, from left to right.
561                    (
562                        Node {
563                            align_items: AlignItems::Center,
564                            ..default()
565                        },
566                        BackgroundColor(CRIMSON.into()),
567                        Children::spawn((
568                            // Display a label for the current setting
569                            Spawn((Text::new("Display Quality"), button_text_style())),
570                            SpawnWith(move |parent: &mut ChildSpawner| {
571                                for quality_setting in [
572                                    DisplayQuality::Low,
573                                    DisplayQuality::Medium,
574                                    DisplayQuality::High,
575                                ] {
576                                    let mut entity = parent.spawn((
577                                        Button,
578                                        Node {
579                                            width: px(150),
580                                            height: px(65),
581                                            ..button_node()
582                                        },
583                                        BackgroundColor(NORMAL_BUTTON),
584                                        quality_setting,
585                                        children![(
586                                            Text::new(format!("{quality_setting:?}")),
587                                            button_text_style(),
588                                        )],
589                                    ));
590                                    if display_quality == quality_setting {
591                                        entity.insert(SelectedOption);
592                                    }
593                                }
594                            })
595                        ))
596                    ),
597                    // Display the back button to return to the settings screen
598                    (
599                        Button,
600                        button_node(),
601                        BackgroundColor(NORMAL_BUTTON),
602                        MenuButtonAction::BackToSettings,
603                        children![(Text::new("Back"), button_text_style())]
604                    )
605                ]
606            )],
607        ));
608    }
609
610    fn sound_settings_menu_setup(mut commands: Commands, volume: Res<Volume>) {
611        let button_node = Node {
612            width: px(200),
613            height: px(65),
614            margin: UiRect::all(px(20)),
615            justify_content: JustifyContent::Center,
616            align_items: AlignItems::Center,
617            ..default()
618        };
619        let button_text_style = (
620            TextFont {
621                font_size: 33.0,
622                ..default()
623            },
624            TextColor(TEXT_COLOR),
625        );
626
627        let volume = *volume;
628        let button_node_clone = button_node.clone();
629        commands.spawn((
630            DespawnOnExit(MenuState::SettingsSound),
631            Node {
632                width: percent(100),
633                height: percent(100),
634                align_items: AlignItems::Center,
635                justify_content: JustifyContent::Center,
636                ..default()
637            },
638            OnSoundSettingsMenuScreen,
639            children![(
640                Node {
641                    flex_direction: FlexDirection::Column,
642                    align_items: AlignItems::Center,
643                    ..default()
644                },
645                BackgroundColor(CRIMSON.into()),
646                children![
647                    (
648                        Node {
649                            align_items: AlignItems::Center,
650                            ..default()
651                        },
652                        BackgroundColor(CRIMSON.into()),
653                        Children::spawn((
654                            Spawn((Text::new("Volume"), button_text_style.clone())),
655                            SpawnWith(move |parent: &mut ChildSpawner| {
656                                for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
657                                    let mut entity = parent.spawn((
658                                        Button,
659                                        Node {
660                                            width: px(30),
661                                            height: px(65),
662                                            ..button_node_clone.clone()
663                                        },
664                                        BackgroundColor(NORMAL_BUTTON),
665                                        Volume(volume_setting),
666                                    ));
667                                    if volume == Volume(volume_setting) {
668                                        entity.insert(SelectedOption);
669                                    }
670                                }
671                            })
672                        ))
673                    ),
674                    (
675                        Button,
676                        button_node,
677                        BackgroundColor(NORMAL_BUTTON),
678                        MenuButtonAction::BackToSettings,
679                        children![(Text::new("Back"), button_text_style)]
680                    )
681                ]
682            )],
683        ));
684    }
Source

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.

Source

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.

§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Source

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
§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Examples found in repository?
examples/ecs/immutable_components.rs (line 181)
135fn demo_3(world: &mut World) {
136    // This is a list of dynamic components we will create.
137    // The first item is the name of the component, and the second is the size
138    // in bytes.
139    let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
140
141    // This pipeline takes our component descriptions, registers them, and gets
142    // their ComponentId's.
143    let my_registered_components = my_dynamic_components
144        .into_iter()
145        .map(|(name, size)| {
146            // SAFETY:
147            // - No drop command is required
148            // - The component will store [u8; size], which is Send + Sync
149            let descriptor = unsafe {
150                ComponentDescriptor::new_with_layout(
151                    name.to_string(),
152                    StorageType::Table,
153                    Layout::array::<u8>(size).unwrap(),
154                    None,
155                    false,
156                    ComponentCloneBehavior::Default,
157                )
158            };
159
160            (name, size, descriptor)
161        })
162        .map(|(name, size, descriptor)| {
163            let component_id = world.register_component_with_descriptor(descriptor);
164
165            (name, size, component_id)
166        })
167        .collect::<Vec<(&str, usize, ComponentId)>>();
168
169    // Now that our components are registered, let's add them to an entity
170    let mut entity = world.spawn_empty();
171
172    for (_name, size, component_id) in &my_registered_components {
173        // We're just storing some zeroes for the sake of demonstration.
174        let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
175
176        OwningPtr::make(data, |ptr| {
177            // SAFETY:
178            // - ComponentId has been taken from the same world
179            // - Array is created to the layout specified in the world
180            unsafe {
181                entity.insert_by_id(*component_id, ptr);
182            }
183        });
184    }
185
186    for (_name, _size, component_id) in &my_registered_components {
187        // With immutable components, we can read the values...
188        assert!(entity.get_by_id(*component_id).is_ok());
189
190        // ...but we cannot gain a mutable reference.
191        assert!(entity.get_mut_by_id(*component_id).is_err());
192
193        // Instead, you must either remove or replace the value.
194    }
195}
Source

pub unsafe fn insert_by_ids<'a, I>( &mut self, component_ids: &[ComponentId], iter_components: I, ) -> &mut EntityWorldMut<'w>
where I: Iterator<Item = OwningPtr<'a>>,

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
§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Examples found in repository?
examples/stress_tests/many_components.rs (line 157)
80fn stress_test(num_entities: u32, num_components: u32, num_systems: u32) {
81    let mut rng = ChaCha8Rng::seed_from_u64(42);
82    let mut app = App::default();
83    let world = app.world_mut();
84
85    // register a bunch of components
86    let component_ids: Vec<ComponentId> = (1..=num_components)
87        .map(|i| {
88            world.register_component_with_descriptor(
89                // SAFETY:
90                // * We don't implement a drop function
91                // * u8 is Sync and Send
92                unsafe {
93                    ComponentDescriptor::new_with_layout(
94                        format!("Component{i}").to_string(),
95                        StorageType::Table,
96                        Layout::new::<u8>(),
97                        None,
98                        true, // is mutable
99                        ComponentCloneBehavior::Default,
100                    )
101                },
102            )
103        })
104        .collect();
105
106    // fill the schedule with systems
107    let mut schedule = Schedule::new(Update);
108    for _ in 1..=num_systems {
109        let num_access_components = rng.random_range(1..10);
110        let access_components: Vec<ComponentId> = component_ids
111            .choose_multiple(&mut rng, num_access_components)
112            .copied()
113            .collect();
114        let system = (QueryParamBuilder::new(|builder| {
115            for &access_component in &access_components {
116                if rand::random::<bool>() {
117                    builder.mut_id(access_component);
118                } else {
119                    builder.ref_id(access_component);
120                }
121            }
122        }),)
123            .build_state(world)
124            .build_any_system(base_system);
125        schedule.add_systems((move || access_components.clone()).pipe(system));
126    }
127
128    // spawn a bunch of entities
129    for _ in 1..=num_entities {
130        let num_components = rng.random_range(1..10);
131        let components: Vec<ComponentId> = component_ids
132            .choose_multiple(&mut rng, num_components)
133            .copied()
134            .collect();
135
136        let mut entity = world.spawn_empty();
137        // We use `ManuallyDrop` here as we need to avoid dropping the u8's when `values` is dropped
138        // since ownership of the values is passed to the world in `insert_by_ids`.
139        // But we do want to deallocate the memory when values is dropped.
140        let mut values: Vec<ManuallyDrop<u8>> = components
141            .iter()
142            .map(|_id| ManuallyDrop::new(rng.random_range(0..255)))
143            .collect();
144        let ptrs: Vec<OwningPtr> = values
145            .iter_mut()
146            .map(|value| {
147                // SAFETY:
148                // * We don't read/write `values` binding after this and values are `ManuallyDrop`,
149                // so we have the right to drop/move the values
150                unsafe { PtrMut::from(value).promote() }
151            })
152            .collect();
153        // SAFETY:
154        // * component_id's are from the same world
155        // * `values` was initialized above, so references are valid
156        unsafe {
157            entity.insert_by_ids(&components, ptrs.into_iter());
158        }
159    }
160
161    // overwrite Update schedule in the app
162    app.add_schedule(schedule);
163    app.add_plugins(MinimalPlugins)
164        .add_plugins(DiagnosticsPlugin)
165        .add_plugins(LogPlugin::default())
166        .add_plugins(FrameTimeDiagnosticsPlugin::default())
167        .add_plugins(LogDiagnosticsPlugin::filtered(HashSet::from_iter([
168            DiagnosticPath::new("fps"),
169        ])));
170    app.run();
171}
More examples
Hide additional examples
examples/ecs/dynamic.rs (line 148)
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}
Source

pub fn take<T>(&mut self) -> Option<T>

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?
examples/ecs/immutable_components.rs (line 43)
30fn demo_1(world: &mut World) {
31    // Immutable components can be inserted just like mutable components.
32    let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
33
34    // But where mutable components can be mutated...
35    let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
36    my_mutable_component.0 = true;
37
38    // ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
39    // is declared as immutable.
40    // let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
41
42    // Instead, you could take or replace the immutable component to update its value.
43    let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
44    my_immutable_component.0 = true;
45    entity.insert(my_immutable_component);
46}
Source

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.

Source

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

§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Source

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.

Source

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.

Source

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 ComponentIds do not exist in the World or if the entity has been despawned while this EntityWorldMut is still alive.

Source

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.

Source

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.

Source

pub fn flush(self) -> Entity

Ensures any commands triggered by the actions of Self are applied, equivalent to World::flush

Source

pub fn world(&self) -> &World

Gets read-only access to the world that the current entity belongs to.

Source

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.

Source

pub fn into_world_mut(self) -> &'w mut World

Returns this entity’s World, consuming itself.

Source

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
});
Source

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.

Source

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.

Source

pub fn entry<'a, T>(&'a mut self) -> ComponentEntry<'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.

Source

pub fn observe<E, B, M>( &mut self, observer: impl IntoObserverSystem<E, B, M>, ) -> &mut EntityWorldMut<'w>
where E: EntityEvent, B: Bundle,

Creates an Observer watching for an EntityEvent of type E whose EntityEvent::event_target targets this entity.

§Panics

If the entity has been despawned while this EntityWorldMut is still alive.

Panics if the given system is an exclusive system.

Examples found in repository?
examples/usage/context_menu.rs (lines 184-194)
146fn background_and_button() -> impl Bundle {
147    (
148        Name::new("background"),
149        Node {
150            width: percent(100),
151            height: percent(100),
152            align_items: AlignItems::Center,
153            justify_content: JustifyContent::Center,
154            ..default()
155        },
156        ZIndex(-10),
157        Children::spawn(SpawnWith(|parent: &mut RelatedSpawner<ChildOf>| {
158            parent
159                .spawn((
160                    Name::new("button"),
161                    Button,
162                    Node {
163                        width: px(250),
164                        height: px(65),
165                        border: UiRect::all(px(5)),
166                        justify_content: JustifyContent::Center,
167                        align_items: AlignItems::Center,
168                        ..default()
169                    },
170                    BorderColor::all(Color::BLACK),
171                    BorderRadius::MAX,
172                    BackgroundColor(Color::BLACK),
173                    children![(
174                        Pickable::IGNORE,
175                        Text::new("Context Menu"),
176                        TextFont {
177                            font_size: 28.0,
178                            ..default()
179                        },
180                        TextColor(Color::WHITE),
181                        TextShadow::default(),
182                    )],
183                ))
184                .observe(|mut event: On<Pointer<Press>>, mut commands: Commands| {
185                    // by default this event would bubble up further leading to the `CloseContextMenus`
186                    // event being triggered and undoing the opening of one here right away.
187                    event.propagate(false);
188
189                    debug!("click: {}", event.pointer_location.position);
190
191                    commands.trigger(OpenContextMenu {
192                        pos: event.pointer_location.position,
193                    });
194                });
195        })),
196    )
197}
Source

pub fn clone_with_opt_out( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static, ) -> &mut EntityWorldMut<'w>

Clones parts of an entity (components, observers, etc.) onto another entity, configured through EntityClonerBuilder.

The other entity will receive all the components of the original that implement Clone or Reflect except those that are denied in the config.

§Example
// Clone all components except ComponentA onto the target.
world.entity_mut(entity).clone_with_opt_out(target, |builder| {
    builder.deny::<ComponentA>();
});

See EntityClonerBuilder<OptOut> for more options.

§Panics
  • If this entity has been despawned while this EntityWorldMut is still alive.
  • If the target entity does not exist.
Source

pub fn clone_with_opt_in( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static, ) -> &mut EntityWorldMut<'w>

Clones parts of an entity (components, observers, etc.) onto another entity, configured through EntityClonerBuilder.

The other entity will receive only the components of the original that implement Clone or Reflect and are allowed in the config.

§Example
// Clone only ComponentA onto the target.
world.entity_mut(entity).clone_with_opt_in(target, |builder| {
    builder.allow::<ComponentA>();
});

See EntityClonerBuilder<OptIn> for more options.

§Panics
  • If this entity has been despawned while this EntityWorldMut is still alive.
  • If the target entity does not exist.
Source

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_opt_out/ opt_in.

§Panics

If this entity has been despawned while this EntityWorldMut is still alive.

Source

pub fn clone_and_spawn_with_opt_out( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static, ) -> Entity

Spawns a clone of this entity and allows configuring cloning behavior using EntityClonerBuilder, returning the Entity of the clone.

The clone will receive all the components of the original that implement Clone or Reflect except those that are denied in the config.

§Example
// Create a clone of an entity but without ComponentA.
let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_out(|builder| {
    builder.deny::<ComponentA>();
});

See EntityClonerBuilder<OptOut> for more options.

§Panics

If this entity has been despawned while this EntityWorldMut is still alive.

Source

pub fn clone_and_spawn_with_opt_in( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static, ) -> Entity

Spawns a clone of this entity and allows configuring cloning behavior using EntityClonerBuilder, returning the Entity of the clone.

The clone will receive only the components of the original that implement Clone or Reflect and are allowed in the config.

§Example
// Create a clone of an entity but only with ComponentA.
let entity_clone = world.entity_mut(entity).clone_and_spawn_with_opt_in(|builder| {
    builder.allow::<ComponentA>();
});

See EntityClonerBuilder<OptIn> for more options.

§Panics

If this entity has been despawned while this EntityWorldMut is still alive.

Source

pub fn clone_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.

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.
Source

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.
Source

pub fn spawned_by(&self) -> MaybeLocation

Returns the source code location from which this entity has last been spawned.

Source

pub fn spawn_tick(&self) -> Tick

Returns the Tick at which this entity has last been spawned.

Source

pub fn reborrow_scope<U>( &mut self, f: impl FnOnce(EntityWorldMut<'_>) -> U, ) -> U

Reborrows this entity in a temporary scope. This is useful for executing a function that requires a EntityWorldMut but you do not want to move out the entity ownership.

Source

pub fn trigger<'t, E>( &mut self, event_fn: impl FnOnce(Entity) -> E, ) -> &mut EntityWorldMut<'w>
where E: EntityEvent, <E as Event>::Trigger<'t>: Default,

Passes the current entity into the given function, and triggers the EntityEvent returned by that function. See EntityCommands::trigger for usage examples

Trait Implementations§

Source§

impl BuildChildrenTransformExt for EntityWorldMut<'_>

Source§

fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityWorldMut<'_>

Change this entity’s parent while preserving this entity’s GlobalTransform by updating its Transform. Read more
Source§

fn remove_parent_in_place(&mut self) -> &mut EntityWorldMut<'_>

Make this entity parentless while preserving this entity’s GlobalTransform by updating its Transform to be equal to its current GlobalTransform. Read more
Source§

impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a>

Source§

fn from(entity: &'a EntityWorldMut<'_>) -> EntityRef<'a>

Converts to this type from the input type.
Source§

impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a, 'static>

Source§

fn from(entity: &'a EntityWorldMut<'_>) -> FilteredEntityRef<'a, 'static>

Converts to this type from the input type.
Source§

impl<'a> From<&'a mut EntityWorldMut<'_>> for EntityMut<'a>

Source§

fn from(entity: &'a mut EntityWorldMut<'_>) -> EntityMut<'a>

Converts to this type from the input type.
Source§

impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a, 'static>

Source§

fn from(entity: &'a mut EntityWorldMut<'_>) -> FilteredEntityMut<'a, 'static>

Converts to this type from the input type.
Source§

impl<'a> From<EntityWorldMut<'a>> for FilteredEntityMut<'a, 'static>

Source§

fn from(entity: EntityWorldMut<'a>) -> FilteredEntityMut<'a, 'static>

Converts to this type from the input type.
Source§

impl<'a> From<EntityWorldMut<'a>> for FilteredEntityRef<'a, 'static>

Source§

fn from(entity: EntityWorldMut<'a>) -> FilteredEntityRef<'a, 'static>

Converts to this type from the input type.
Source§

impl<'w> From<EntityWorldMut<'w>> for EntityMut<'w>

Source§

fn from(entity: EntityWorldMut<'w>) -> EntityMut<'w>

Converts to this type from the input type.
Source§

impl<'w> From<EntityWorldMut<'w>> for EntityRef<'w>

Source§

fn from(entity: EntityWorldMut<'w>) -> EntityRef<'w>

Converts to this type from the input type.

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> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts 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>

Converts 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)

Converts &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)

Converts &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 T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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>

Convert 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)

Convert &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)

Convert &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
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows 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
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows 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
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .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
where Self: BorrowMut<B>, B: ?Sized,

Calls .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
where Self: AsRef<R>, R: ?Sized,

Calls .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
where Self: AsMut<R>, R: ?Sized,

Calls .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
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,