pub struct EntityCommands<'a> { /* private fields */ }Expand description
A list of commands that will be run to modify an Entity.
§Note
Most Commands (and thereby EntityCommands) are deferred:
when you call the command, if it requires mutable access to the World
(that is, if it removes, adds, or changes something), it’s not executed immediately.
Instead, the command is added to a “command queue.”
The command queue is applied later
when the ApplyDeferred system runs.
Commands are executed one-by-one so that
each command can have exclusive access to the World.
§Fallible
Due to their deferred nature, an entity you’re trying to change with an EntityCommand
can be despawned by the time the command is executed.
All deferred entity commands will check whether the entity exists at the time of execution and will return an error if it doesn’t.
§Error handling
An EntityCommand can return a Result,
which will be passed to an error handler if the Result is an error.
The default error handler panics. It can be configured via
the DefaultErrorHandler resource.
Alternatively, you can customize the error handler for a specific command
by calling EntityCommands::queue_handled.
The error module provides some simple error handlers for convenience.
Implementations§
Source§impl<'a> EntityCommands<'a>
impl<'a> EntityCommands<'a>
Sourcepub fn with_children(
&mut self,
func: impl FnOnce(&mut RelatedSpawnerCommands<'_, ChildOf>),
) -> &mut EntityCommands<'a>
pub fn with_children( &mut self, func: impl FnOnce(&mut RelatedSpawnerCommands<'_, ChildOf>), ) -> &mut EntityCommands<'a>
Spawns children of this entity (with a ChildOf relationship) by taking a function that operates on a ChildSpawner.
Examples found in repository?
83fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut state: ResMut<State>) {
84 let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");
85 state.handle = font_handle.clone();
86 commands.spawn(Camera2d);
87 commands
88 .spawn((
89 Node {
90 position_type: PositionType::Absolute,
91 bottom: Val::ZERO,
92 ..default()
93 },
94 BackgroundColor(Color::NONE),
95 ))
96 .with_children(|parent| {
97 parent.spawn((
98 Text::new("a"),
99 TextFont {
100 font: font_handle,
101 font_size: 50.0,
102 ..default()
103 },
104 TextColor(YELLOW.into()),
105 ));
106 });
107 // We're seeding the PRNG here to make this example deterministic for testing purposes.
108 // This isn't strictly required in practical use unless you need your app to be deterministic.
109 commands.insert_resource(SeededRng(ChaCha8Rng::seed_from_u64(19878367467713)));
110}More examples
44fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
45 let image = asset_server.load("textures/fantasy_ui_borders/panel-border-010.png");
46
47 let slicer = TextureSlicer {
48 border: BorderRect::all(22.0),
49 center_scale_mode: SliceScaleMode::Stretch,
50 sides_scale_mode: SliceScaleMode::Stretch,
51 max_corner_scale: 1.0,
52 };
53 // ui camera
54 commands.spawn(Camera2d);
55 commands
56 .spawn(Node {
57 width: percent(100),
58 height: percent(100),
59 align_items: AlignItems::Center,
60 justify_content: JustifyContent::Center,
61 ..default()
62 })
63 .with_children(|parent| {
64 for [w, h] in [[150.0, 150.0], [300.0, 150.0], [150.0, 300.0]] {
65 parent
66 .spawn((
67 Button,
68 ImageNode {
69 image: image.clone(),
70 image_mode: NodeImageMode::Sliced(slicer.clone()),
71 ..default()
72 },
73 Node {
74 width: px(w),
75 height: px(h),
76 // horizontally center child text
77 justify_content: JustifyContent::Center,
78 // vertically center child text
79 align_items: AlignItems::Center,
80 margin: UiRect::all(px(20)),
81 ..default()
82 },
83 ))
84 .with_child((
85 Text::new("Button"),
86 TextFont {
87 font: asset_server.load("fonts/FiraSans-Bold.ttf"),
88 font_size: 33.0,
89 ..default()
90 },
91 TextColor(Color::srgb(0.9, 0.9, 0.9)),
92 ));
93 }
94 });
95}17fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
18 let image = asset_server.load_with_settings(
19 "textures/fantasy_ui_borders/numbered_slices.png",
20 |settings: &mut ImageLoaderSettings| {
21 // Need to use nearest filtering to avoid bleeding between the slices with tiling
22 settings.sampler = ImageSampler::nearest();
23 },
24 );
25
26 let slicer = TextureSlicer {
27 // `numbered_slices.png` is 48 pixels square. `BorderRect::square(16.)` insets the slicing line from each edge by 16 pixels, resulting in nine slices that are each 16 pixels square.
28 border: BorderRect::all(16.),
29 // With `SliceScaleMode::Tile` the side and center slices are tiled to fill the side and center sections of the target.
30 // And with a `stretch_value` of `1.` the tiles will have the same size as the corresponding slices in the source image.
31 center_scale_mode: SliceScaleMode::Tile { stretch_value: 1. },
32 sides_scale_mode: SliceScaleMode::Tile { stretch_value: 1. },
33 ..default()
34 };
35
36 // ui camera
37 commands.spawn(Camera2d);
38
39 commands
40 .spawn(Node {
41 width: percent(100),
42 height: percent(100),
43 justify_content: JustifyContent::Center,
44 align_content: AlignContent::Center,
45 flex_wrap: FlexWrap::Wrap,
46 column_gap: px(10),
47 row_gap: px(10),
48 ..default()
49 })
50 .with_children(|parent| {
51 for [columns, rows] in [[3, 3], [4, 4], [5, 4], [4, 5], [5, 5]] {
52 for (flip_x, flip_y) in [(false, false), (false, true), (true, false), (true, true)]
53 {
54 parent.spawn((
55 ImageNode {
56 image: image.clone(),
57 flip_x,
58 flip_y,
59 image_mode: NodeImageMode::Sliced(slicer.clone()),
60 ..default()
61 },
62 Node {
63 width: px(16 * columns),
64 height: px(16 * rows),
65 ..default()
66 },
67 ));
68 }
69 }
70 });
71}29fn setup(
30 mut commands: Commands,
31 mut meshes: ResMut<Assets<Mesh>>,
32 mut materials: ResMut<Assets<ColorMaterial>>,
33) {
34 commands.spawn(Camera2d);
35
36 commands
37 .spawn((
38 Node {
39 width: Val::Percent(100.0),
40 height: Val::Percent(100.0),
41 align_items: AlignItems::Center,
42 justify_content: JustifyContent::Start,
43 ..default()
44 },
45 Pickable::IGNORE,
46 ))
47 .with_children(|parent| {
48 parent
49 .spawn((
50 DraggableButton,
51 Node {
52 width: Val::Px(BUTTON_WIDTH),
53 height: Val::Px(BUTTON_HEIGHT),
54 margin: UiRect::all(Val::Px(10.0)),
55 justify_content: JustifyContent::Center,
56 align_items: AlignItems::Center,
57 ..default()
58 },
59 BackgroundColor(Color::srgb(1.0, 0.0, 0.0)),
60 ))
61 .with_child((
62 Text::new("Drag from me"),
63 TextColor(Color::WHITE),
64 Pickable::IGNORE,
65 ))
66 .observe(
67 |mut event: On<Pointer<DragStart>>,
68 mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| {
69 button_color.0 = Color::srgb(1.0, 0.5, 0.0);
70 event.propagate(false);
71 },
72 )
73 .observe(
74 |mut event: On<Pointer<DragEnd>>,
75 mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| {
76 button_color.0 = Color::srgb(1.0, 0.0, 0.0);
77 event.propagate(false);
78 },
79 );
80 });
81
82 commands
83 .spawn((
84 DropArea,
85 Mesh2d(meshes.add(Rectangle::new(AREA_SIZE, AREA_SIZE))),
86 MeshMaterial2d(materials.add(Color::srgb(0.1, 0.4, 0.1))),
87 Transform::IDENTITY,
88 children![(
89 Text2d::new("Drop here"),
90 TextFont::from_font_size(50.),
91 TextColor(Color::BLACK),
92 Pickable::IGNORE,
93 Transform::from_translation(Vec3::Z),
94 )],
95 ))
96 .observe(on_drag_enter)
97 .observe(on_drag_over)
98 .observe(on_drag_drop)
99 .observe(on_drag_leave);
100}47fn setup(
48 mut commands: Commands,
49 asset_server: Res<AssetServer>,
50 mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
51) {
52 let texture_handle = asset_server.load("textures/fantasy_ui_borders/border_sheet.png");
53 let atlas_layout =
54 TextureAtlasLayout::from_grid(UVec2::new(50, 50), 6, 6, Some(UVec2::splat(2)), None);
55 let atlas_layout_handle = texture_atlases.add(atlas_layout);
56
57 let slicer = TextureSlicer {
58 border: BorderRect::all(24.0),
59 center_scale_mode: SliceScaleMode::Stretch,
60 sides_scale_mode: SliceScaleMode::Stretch,
61 max_corner_scale: 1.0,
62 };
63 // ui camera
64 commands.spawn(Camera2d);
65 commands
66 .spawn(Node {
67 width: percent(100),
68 height: percent(100),
69 align_items: AlignItems::Center,
70 justify_content: JustifyContent::Center,
71 ..default()
72 })
73 .with_children(|parent| {
74 for (idx, [w, h]) in [
75 (0, [150.0, 150.0]),
76 (7, [300.0, 150.0]),
77 (13, [150.0, 300.0]),
78 ] {
79 parent
80 .spawn((
81 Button,
82 ImageNode::from_atlas_image(
83 texture_handle.clone(),
84 TextureAtlas {
85 index: idx,
86 layout: atlas_layout_handle.clone(),
87 },
88 )
89 .with_mode(NodeImageMode::Sliced(slicer.clone())),
90 Node {
91 width: px(w),
92 height: px(h),
93 // horizontally center child text
94 justify_content: JustifyContent::Center,
95 // vertically center child text
96 align_items: AlignItems::Center,
97 margin: UiRect::all(px(20)),
98 ..default()
99 },
100 ))
101 .with_children(|parent| {
102 parent.spawn((
103 Text::new("Button"),
104 TextFont {
105 font: asset_server.load("fonts/FiraSans-Bold.ttf"),
106 font_size: 33.0,
107 ..default()
108 },
109 TextColor(Color::srgb(0.9, 0.9, 0.9)),
110 ));
111 });
112 }
113 });
114}68fn setup(mut commands: Commands) {
69 // ui camera
70 commands.spawn(Camera2d);
71 commands
72 .spawn(Node {
73 width: percent(100),
74 height: percent(100),
75 display: Display::Flex,
76 flex_direction: FlexDirection::Column,
77 align_items: AlignItems::Center,
78 justify_content: JustifyContent::Center,
79 row_gap: px(6),
80 ..default()
81 })
82 .observe(
83 |mut event: On<Pointer<Click>>, mut focus: ResMut<InputFocus>| {
84 focus.0 = None;
85 event.propagate(false);
86 },
87 )
88 .with_children(|parent| {
89 for (label, tab_group, indices) in [
90 // In this group all the buttons have the same `TabIndex` so they will be visited according to their order as children.
91 ("TabGroup 0", TabGroup::new(0), [0, 0, 0, 0]),
92 // In this group the `TabIndex`s are reversed so the buttons will be visited in right-to-left order.
93 ("TabGroup 2", TabGroup::new(2), [3, 2, 1, 0]),
94 // In this group the orders of the indices and buttons match so the buttons will be visited in left-to-right order.
95 ("TabGroup 1", TabGroup::new(1), [0, 1, 2, 3]),
96 // Visit the modal group's buttons in an arbitrary order.
97 ("Modal TabGroup", TabGroup::modal(), [0, 3, 1, 2]),
98 ] {
99 parent.spawn(Text::new(label));
100 parent
101 .spawn((
102 Node {
103 display: Display::Flex,
104 flex_direction: FlexDirection::Row,
105 column_gap: px(6),
106 margin: UiRect {
107 bottom: px(10),
108 ..default()
109 },
110 ..default()
111 },
112 tab_group,
113 ))
114 .with_children(|parent| {
115 for i in indices {
116 parent
117 .spawn((
118 Button,
119 Node {
120 width: px(200),
121 height: px(65),
122 border: UiRect::all(px(5)),
123 justify_content: JustifyContent::Center,
124 align_items: AlignItems::Center,
125 ..default()
126 },
127 BorderColor::all(Color::BLACK),
128 BackgroundColor(NORMAL_BUTTON),
129 TabIndex(i),
130 children![(
131 Text::new(format!("TabIndex {i}")),
132 TextFont {
133 font_size: 20.0,
134 ..default()
135 },
136 TextColor(Color::srgb(0.9, 0.9, 0.9)),
137 )],
138 ))
139 .observe(
140 |mut click: On<Pointer<Click>>,
141 mut focus: ResMut<InputFocus>| {
142 focus.0 = Some(click.entity);
143 click.propagate(false);
144 },
145 );
146 }
147 });
148 }
149 });
150}Sourcepub fn add_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'a>
pub fn add_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'a>
Adds the given children to this entity.
Sourcepub fn clear_children(&mut self) -> &mut EntityCommands<'a>
👎Deprecated: Use detach_all_children() instead
pub fn clear_children(&mut self) -> &mut EntityCommands<'a>
Removes all the children from this entity.
See also detach_all_related
Sourcepub fn detach_all_children(&mut self) -> &mut EntityCommands<'a>
pub fn detach_all_children(&mut self) -> &mut EntityCommands<'a>
Removes all the parent-child relationships from this entity.
To despawn the child entities, instead use EntityWorldMut::despawn_children.
See also detach_all_related
Sourcepub fn insert_children(
&mut self,
index: usize,
children: &[Entity],
) -> &mut EntityCommands<'a>
pub fn insert_children( &mut self, index: usize, children: &[Entity], ) -> &mut EntityCommands<'a>
Insert children at specific index.
See also insert_related.
Sourcepub fn insert_child(
&mut self,
index: usize,
child: Entity,
) -> &mut EntityCommands<'a>
pub fn insert_child( &mut self, index: usize, child: Entity, ) -> &mut EntityCommands<'a>
Insert children at specific index.
See also insert_related.
Sourcepub fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'a>
pub fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'a>
Adds the given child to this entity.
Sourcepub fn remove_children(
&mut self,
children: &[Entity],
) -> &mut EntityCommands<'a>
👎Deprecated: Use detach_children() instead
pub fn remove_children( &mut self, children: &[Entity], ) -> &mut EntityCommands<'a>
Removes the relationship between this entity and the given entities.
Sourcepub fn detach_children(
&mut self,
children: &[Entity],
) -> &mut EntityCommands<'a>
pub fn detach_children( &mut self, children: &[Entity], ) -> &mut EntityCommands<'a>
Removes the parent-child relationship between this entity and the given entities. Does not despawn the children.
Sourcepub fn remove_child(&mut self, child: Entity) -> &mut EntityCommands<'a>
👎Deprecated: Use detach_child() instead
pub fn remove_child(&mut self, child: Entity) -> &mut EntityCommands<'a>
Removes the relationship between this entity and the given entity.
Sourcepub fn detach_child(&mut self, child: Entity) -> &mut EntityCommands<'a>
pub fn detach_child(&mut self, child: Entity) -> &mut EntityCommands<'a>
Removes the parent-child relationship between this entity and the given entity. Does not despawn the child.
Sourcepub fn replace_children(
&mut self,
children: &[Entity],
) -> &mut EntityCommands<'a>
pub fn replace_children( &mut self, children: &[Entity], ) -> &mut EntityCommands<'a>
Replaces the children on this entity with a new list of children.
Sourcepub fn replace_children_with_difference(
&mut self,
entities_to_unrelate: &[Entity],
entities_to_relate: &[Entity],
newly_related_entities: &[Entity],
) -> &mut EntityCommands<'a>
pub fn replace_children_with_difference( &mut self, entities_to_unrelate: &[Entity], entities_to_relate: &[Entity], newly_related_entities: &[Entity], ) -> &mut EntityCommands<'a>
Replaces all the related entities with a new set of entities.
§Warning
Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
Refer to EntityWorldMut::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.
Sourcepub fn with_child(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn with_child(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Spawns the passed bundle and adds it to this entity as a child.
For efficient spawning of multiple children, use with_children.
Examples found in repository?
16fn setup(
17 mut commands: Commands,
18 mut meshes: ResMut<Assets<Mesh>>,
19 mut materials: ResMut<Assets<StandardMaterial>>,
20) {
21 // camera
22 commands.spawn((
23 Camera3d::default(),
24 Transform::from_xyz(0.2, 1.5, 2.5).looking_at(Vec3::ZERO, Vec3::Y),
25 ));
26
27 // plane
28 commands.spawn((
29 Mesh3d(meshes.add(Plane3d::default().mesh().size(100.0, 100.0))),
30 MeshMaterial3d(materials.add(StandardMaterial {
31 base_color: Color::srgb(0.2, 0.2, 0.2),
32 perceptual_roughness: 0.08,
33 ..default()
34 })),
35 ));
36
37 const COUNT: usize = 6;
38 let position_range = -2.0..2.0;
39 let radius_range = 0.0..0.4;
40 let pos_len = position_range.end - position_range.start;
41 let radius_len = radius_range.end - radius_range.start;
42 let mesh = meshes.add(Sphere::new(1.0).mesh().uv(120, 64));
43
44 for i in 0..COUNT {
45 let percent = i as f32 / COUNT as f32;
46 let radius = radius_range.start + percent * radius_len;
47
48 // sphere light
49 commands
50 .spawn((
51 Mesh3d(mesh.clone()),
52 MeshMaterial3d(materials.add(StandardMaterial {
53 base_color: Color::srgb(0.5, 0.5, 1.0),
54 unlit: true,
55 ..default()
56 })),
57 Transform::from_xyz(position_range.start + percent * pos_len, 0.3, 0.0)
58 .with_scale(Vec3::splat(radius)),
59 ))
60 .with_child(PointLight {
61 radius,
62 color: Color::srgb(0.2, 0.2, 1.0),
63 ..default()
64 });
65 }
66}More examples
44fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
45 let image = asset_server.load("textures/fantasy_ui_borders/panel-border-010.png");
46
47 let slicer = TextureSlicer {
48 border: BorderRect::all(22.0),
49 center_scale_mode: SliceScaleMode::Stretch,
50 sides_scale_mode: SliceScaleMode::Stretch,
51 max_corner_scale: 1.0,
52 };
53 // ui camera
54 commands.spawn(Camera2d);
55 commands
56 .spawn(Node {
57 width: percent(100),
58 height: percent(100),
59 align_items: AlignItems::Center,
60 justify_content: JustifyContent::Center,
61 ..default()
62 })
63 .with_children(|parent| {
64 for [w, h] in [[150.0, 150.0], [300.0, 150.0], [150.0, 300.0]] {
65 parent
66 .spawn((
67 Button,
68 ImageNode {
69 image: image.clone(),
70 image_mode: NodeImageMode::Sliced(slicer.clone()),
71 ..default()
72 },
73 Node {
74 width: px(w),
75 height: px(h),
76 // horizontally center child text
77 justify_content: JustifyContent::Center,
78 // vertically center child text
79 align_items: AlignItems::Center,
80 margin: UiRect::all(px(20)),
81 ..default()
82 },
83 ))
84 .with_child((
85 Text::new("Button"),
86 TextFont {
87 font: asset_server.load("fonts/FiraSans-Bold.ttf"),
88 font_size: 33.0,
89 ..default()
90 },
91 TextColor(Color::srgb(0.9, 0.9, 0.9)),
92 ));
93 }
94 });
95}29fn setup(
30 mut commands: Commands,
31 mut meshes: ResMut<Assets<Mesh>>,
32 mut materials: ResMut<Assets<ColorMaterial>>,
33) {
34 commands.spawn(Camera2d);
35
36 commands
37 .spawn((
38 Node {
39 width: Val::Percent(100.0),
40 height: Val::Percent(100.0),
41 align_items: AlignItems::Center,
42 justify_content: JustifyContent::Start,
43 ..default()
44 },
45 Pickable::IGNORE,
46 ))
47 .with_children(|parent| {
48 parent
49 .spawn((
50 DraggableButton,
51 Node {
52 width: Val::Px(BUTTON_WIDTH),
53 height: Val::Px(BUTTON_HEIGHT),
54 margin: UiRect::all(Val::Px(10.0)),
55 justify_content: JustifyContent::Center,
56 align_items: AlignItems::Center,
57 ..default()
58 },
59 BackgroundColor(Color::srgb(1.0, 0.0, 0.0)),
60 ))
61 .with_child((
62 Text::new("Drag from me"),
63 TextColor(Color::WHITE),
64 Pickable::IGNORE,
65 ))
66 .observe(
67 |mut event: On<Pointer<DragStart>>,
68 mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| {
69 button_color.0 = Color::srgb(1.0, 0.5, 0.0);
70 event.propagate(false);
71 },
72 )
73 .observe(
74 |mut event: On<Pointer<DragEnd>>,
75 mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| {
76 button_color.0 = Color::srgb(1.0, 0.0, 0.0);
77 event.propagate(false);
78 },
79 );
80 });
81
82 commands
83 .spawn((
84 DropArea,
85 Mesh2d(meshes.add(Rectangle::new(AREA_SIZE, AREA_SIZE))),
86 MeshMaterial2d(materials.add(Color::srgb(0.1, 0.4, 0.1))),
87 Transform::IDENTITY,
88 children![(
89 Text2d::new("Drop here"),
90 TextFont::from_font_size(50.),
91 TextColor(Color::BLACK),
92 Pickable::IGNORE,
93 Transform::from_translation(Vec3::Z),
94 )],
95 ))
96 .observe(on_drag_enter)
97 .observe(on_drag_over)
98 .observe(on_drag_drop)
99 .observe(on_drag_leave);
100}16fn setup(mut commands: Commands) {
17 commands.spawn(Camera2d);
18 commands
19 .spawn((Node {
20 display: Display::Grid,
21 align_self: AlignSelf::Center,
22 justify_self: JustifySelf::Center,
23 ..Default::default()
24 }, Pickable::IGNORE, BackgroundColor(Color::srgb(0.4, 0.4, 0.4))))
25 .with_children(|parent| {
26 let tile_colors = [
27 Color::srgb(0.2, 0.2, 0.8),
28 Color::srgb(0.8, 0.2, 0.2)
29 ];
30 for column in 0..COLUMNS {
31 for row in 0..ROWS {
32 let i = column + row * COLUMNS;
33 let tile_color = tile_colors[((row % 2) + column) as usize % tile_colors.len()];
34 let tile_border_color = tile_color.darker(0.025);
35 parent
36 .spawn((
37 Node {
38 width: Val::Px(TILE_SIZE),
39 height: Val::Px(TILE_SIZE),
40 border: UiRect::all(Val::Px(4.)),
41 grid_row: GridPlacement::start(row + 1),
42 grid_column: GridPlacement::start(column + 1),
43 align_items: AlignItems::Center,
44 justify_content: JustifyContent::Center,
45 ..Default::default()
46 },
47 BorderColor::all(tile_border_color),
48 BackgroundColor(tile_color),
49 Outline {
50 width: Val::Px(2.),
51 offset: Val::ZERO,
52 color: Color::NONE,
53 },
54 Pickable {
55 should_block_lower: false,
56 is_hoverable: true,
57 },
58 GlobalZIndex::default()
59 ))
60 .observe(move |on_over: On<Pointer<Over>>, mut query: Query<(&mut BackgroundColor, &mut BorderColor)>| {
61 if let Ok((mut background_color, mut border_color)) = query.get_mut(on_over.event_target()) {
62 background_color.0 = tile_color.lighter(0.1);
63 border_color.set_all(tile_border_color.lighter(0.1));
64 }
65 })
66 .observe(move |on_out: On<Pointer<Out>>, mut query: Query<(&mut BackgroundColor, &mut BorderColor)>| {
67 if let Ok((mut background_color, mut border_color)) = query.get_mut(on_out.event_target()) {
68 background_color.0 = tile_color;
69 border_color.set_all(tile_border_color);
70 }
71 })
72 .observe(|on_drag_start: On<Pointer<DragStart>>, mut query: Query<(&mut Outline, &mut GlobalZIndex)>| {
73 if let Ok((mut outline, mut global_zindex, )) = query.get_mut(on_drag_start.event_target()) {
74 outline.color = Color::WHITE;
75 global_zindex.0 = 1;
76 }
77 })
78 .observe(|on_drag: On<Pointer<Drag>>, mut query: Query<&mut UiTransform>| {
79 if let Ok(mut transform) = query.get_mut(on_drag.event_target()) {
80 transform.translation = Val2::px(on_drag.distance.x, on_drag.distance.y);
81 }
82 })
83 .observe(move |on_drag_end: On<Pointer<DragEnd>>, mut query: Query<(&mut UiTransform, &mut Outline, &mut GlobalZIndex)>| {
84 if let Ok((mut transform, mut outline, mut global_zindex)) = query.get_mut(on_drag_end.event_target()) {
85 transform.translation = Val2::ZERO;
86 outline.color = Color::NONE;
87 global_zindex.0 = 0;
88 }
89 })
90 .observe(|on_drag_drop: On<Pointer<DragDrop>>, mut query: Query<&mut Node>| {
91 if let Ok([mut a, mut b]) = query.get_many_mut([on_drag_drop.event_target(), on_drag_drop.dropped]) {
92 core::mem::swap(&mut a.grid_row, &mut b.grid_row);
93 core::mem::swap(&mut a.grid_column, &mut b.grid_column);
94 }
95 })
96 .with_child((Text::new(format!("{i}")), Pickable::IGNORE));
97 }
98 }
99 });
100}Source§impl<'a> EntityCommands<'a>
impl<'a> EntityCommands<'a>
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.
Relates the given entity to this with the relation R.
See add_related if you want to relate more than one entity.
Removes the relation R between this entity and the given entities.
Replaces all the related entities with the given set of new related entities.
Replaces all the related entities with a new set of entities.
§Warning
Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
Refer to EntityWorldMut::replace_related_with_difference for a list of these invariants.
§Panics
Panics when debug assertions are enable, an invariant is are broken and the command is executed.
Despawns entities that relate to this one via the given RelationshipTarget.
This entity will not be despawned.
Sourcepub fn despawn_children(&mut self) -> &mut EntityCommands<'a>
pub fn despawn_children(&mut self) -> &mut EntityCommands<'a>
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.
Sourcepub fn insert_recursive<S>(
&mut self,
bundle: impl Bundle + Clone,
) -> &mut EntityCommands<'a>where
S: RelationshipTarget,
pub fn insert_recursive<S>(
&mut self,
bundle: impl Bundle + Clone,
) -> &mut EntityCommands<'a>where
S: RelationshipTarget,
Inserts a component or bundle of components into the entity and all related entities,
traversing the relationship tracked in S in a breadth-first manner.
§Warning
This method should only be called on relationships that form a tree-like structure. Any cycles will cause this method to loop infinitely.
Sourcepub fn remove_recursive<S, B>(&mut self) -> &mut EntityCommands<'a>where
S: RelationshipTarget,
B: Bundle,
pub fn remove_recursive<S, B>(&mut self) -> &mut EntityCommands<'a>where
S: RelationshipTarget,
B: Bundle,
Removes a component or bundle of components of type B from the entity and all related entities,
traversing the relationship tracked in S in a breadth-first manner.
§Warning
This method should only be called on relationships that form a tree-like structure. Any cycles will cause this method to loop infinitely.
Source§impl<'a> EntityCommands<'a>
impl<'a> EntityCommands<'a>
Sourcepub fn id(&self) -> Entity
pub fn id(&self) -> Entity
Returns the Entity id of the entity.
§Example
fn my_system(mut commands: Commands) {
let entity_id = commands.spawn_empty().id();
}Examples found in repository?
22fn setup(
23 mut commands: Commands,
24 mut meshes: ResMut<Assets<Mesh>>,
25 mut materials: ResMut<Assets<StandardMaterial>>,
26 mut animations: ResMut<Assets<AnimationClip>>,
27 mut graphs: ResMut<Assets<AnimationGraph>>,
28) {
29 // Camera
30 commands.spawn((
31 Camera3d::default(),
32 Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
33 ));
34
35 // Light
36 commands.spawn((
37 PointLight {
38 intensity: 500_000.0,
39 ..default()
40 },
41 Transform::from_xyz(0.0, 2.5, 0.0),
42 ));
43
44 // Let's use the `Name` component to target entities. We can use anything we
45 // like, but names are convenient.
46 let planet = Name::new("planet");
47 let orbit_controller = Name::new("orbit_controller");
48 let satellite = Name::new("satellite");
49
50 // Creating the animation
51 let mut animation = AnimationClip::default();
52 // A curve can modify a single part of a transform: here, the translation.
53 let planet_animation_target_id = AnimationTargetId::from_name(&planet);
54 animation.add_curve_to_target(
55 planet_animation_target_id,
56 AnimatableCurve::new(
57 animated_field!(Transform::translation),
58 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
59 Vec3::new(1.0, 0.0, 1.0),
60 Vec3::new(-1.0, 0.0, 1.0),
61 Vec3::new(-1.0, 0.0, -1.0),
62 Vec3::new(1.0, 0.0, -1.0),
63 // in case seamless looping is wanted, the last keyframe should
64 // be the same as the first one
65 Vec3::new(1.0, 0.0, 1.0),
66 ]))
67 .expect("should be able to build translation curve because we pass in valid samples"),
68 ),
69 );
70 // Or it can modify the rotation of the transform.
71 // To find the entity to modify, the hierarchy will be traversed looking for
72 // an entity with the right name at each level.
73 let orbit_controller_animation_target_id =
74 AnimationTargetId::from_names([planet.clone(), orbit_controller.clone()].iter());
75 animation.add_curve_to_target(
76 orbit_controller_animation_target_id,
77 AnimatableCurve::new(
78 animated_field!(Transform::rotation),
79 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
80 Quat::IDENTITY,
81 Quat::from_axis_angle(Vec3::Y, PI / 2.),
82 Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
83 Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
84 Quat::IDENTITY,
85 ]))
86 .expect("Failed to build rotation curve"),
87 ),
88 );
89 // If a curve in an animation is shorter than the other, it will not repeat
90 // until all other curves are finished. In that case, another animation should
91 // be created for each part that would have a different duration / period.
92 let satellite_animation_target_id = AnimationTargetId::from_names(
93 [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
94 );
95 animation.add_curve_to_target(
96 satellite_animation_target_id,
97 AnimatableCurve::new(
98 animated_field!(Transform::scale),
99 UnevenSampleAutoCurve::new(
100 [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
101 .into_iter()
102 .zip([
103 Vec3::splat(0.8),
104 Vec3::splat(1.2),
105 Vec3::splat(0.8),
106 Vec3::splat(1.2),
107 Vec3::splat(0.8),
108 Vec3::splat(1.2),
109 Vec3::splat(0.8),
110 Vec3::splat(1.2),
111 Vec3::splat(0.8),
112 ]),
113 )
114 .expect("Failed to build scale curve"),
115 ),
116 );
117 // There can be more than one curve targeting the same entity path.
118 animation.add_curve_to_target(
119 AnimationTargetId::from_names(
120 [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
121 ),
122 AnimatableCurve::new(
123 animated_field!(Transform::rotation),
124 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
125 Quat::IDENTITY,
126 Quat::from_axis_angle(Vec3::Y, PI / 2.),
127 Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
128 Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
129 Quat::IDENTITY,
130 ]))
131 .expect("should be able to build translation curve because we pass in valid samples"),
132 ),
133 );
134
135 // Create the animation graph
136 let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));
137
138 // Create the animation player, and set it to repeat
139 let mut player = AnimationPlayer::default();
140 player.play(animation_index).repeat();
141
142 // Create the scene that will be animated
143 // First entity is the planet
144 let planet_entity = commands
145 .spawn((
146 Mesh3d(meshes.add(Sphere::default())),
147 MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
148 // Add the animation graph and player
149 planet,
150 AnimationGraphHandle(graphs.add(graph)),
151 player,
152 ))
153 .id();
154 commands.entity(planet_entity).insert((
155 planet_animation_target_id,
156 AnimatedBy(planet_entity),
157 children![(
158 Transform::default(),
159 Visibility::default(),
160 orbit_controller,
161 orbit_controller_animation_target_id,
162 AnimatedBy(planet_entity),
163 children![(
164 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
165 MeshMaterial3d(materials.add(Color::srgb(0.3, 0.9, 0.3))),
166 Transform::from_xyz(1.5, 0.0, 0.0),
167 satellite_animation_target_id,
168 AnimatedBy(planet_entity),
169 satellite,
170 )],
171 )],
172 ));
173}Sourcepub fn reborrow(&mut self) -> EntityCommands<'_>
pub fn reborrow(&mut self) -> EntityCommands<'_>
Returns an EntityCommands with a smaller lifetime.
This is useful if you have &mut EntityCommands but you need EntityCommands.
Sourcepub fn entry<T>(&mut self) -> EntityEntryCommands<'_, T>where
T: Component,
pub fn entry<T>(&mut self) -> EntityEntryCommands<'_, T>where
T: Component,
Get an EntityEntryCommands for the Component T,
allowing you to modify it or insert it if it isn’t already present.
See also insert_if_new,
which lets you insert a Bundle without overwriting it.
§Example
#[derive(Component)]
struct Level(u32);
#[derive(Component, Default)]
struct Mana {
max: u32,
current: u32,
}
fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
// If a component already exists then modify it, otherwise insert a default value
commands
.entity(player.entity)
.entry::<Level>()
.and_modify(|mut lvl| lvl.0 += 1)
.or_insert(Level(0));
// Add a default value if none exists, and then modify the existing or new value
commands
.entity(player.entity)
.entry::<Mana>()
.or_default()
.and_modify(|mut mana| {
mana.max += 10;
mana.current = mana.max;
});
}
Sourcepub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity.
This will overwrite any previous value(s) of the same component type.
See EntityCommands::insert_if_new to keep the old value instead.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can insert individual components:
.insert(Defense(10))
// You can also insert pre-defined bundles of components:
.insert(CombatBundle {
health: Health(100),
strength: Strength(40),
})
// You can also insert tuples of components and bundles.
// This is equivalent to the calls above:
.insert((
Defense(10),
CombatBundle {
health: Health(100),
strength: Strength(40),
},
));
}Examples found in repository?
31fn screenshot_saving(
32 mut commands: Commands,
33 screenshot_saving: Query<Entity, With<Capturing>>,
34 window: Single<Entity, With<Window>>,
35) {
36 match screenshot_saving.iter().count() {
37 0 => {
38 commands.entity(*window).remove::<CursorIcon>();
39 }
40 x if x > 0 => {
41 commands
42 .entity(*window)
43 .insert(CursorIcon::from(SystemCursorIcon::Progress));
44 }
45 _ => {}
46 }
47}More examples
48fn focus_system(
49 mut commands: Commands,
50 focus: Res<InputFocus>,
51 mut query: Query<Entity, With<Button>>,
52) {
53 if focus.is_changed() {
54 for button in query.iter_mut() {
55 if focus.0 == Some(button) {
56 commands.entity(button).insert(Outline {
57 color: Color::WHITE,
58 width: px(2),
59 offset: px(2),
60 });
61 } else {
62 commands.entity(button).remove::<Outline>();
63 }
64 }
65 }
66}72fn update_bloom_settings(
73 camera: Single<(Entity, &Tonemapping, Option<&mut Bloom>), With<Camera>>,
74 mut text: Single<&mut Text>,
75 mut commands: Commands,
76 keycode: Res<ButtonInput<KeyCode>>,
77 time: Res<Time>,
78) {
79 let (camera_entity, tonemapping, bloom) = camera.into_inner();
80
81 match bloom {
82 Some(mut bloom) => {
83 text.0 = "Bloom (Toggle: Space)\n".to_string();
84 text.push_str(&format!("(Q/A) Intensity: {:.2}\n", bloom.intensity));
85 text.push_str(&format!(
86 "(W/S) Low-frequency boost: {:.2}\n",
87 bloom.low_frequency_boost
88 ));
89 text.push_str(&format!(
90 "(E/D) Low-frequency boost curvature: {:.2}\n",
91 bloom.low_frequency_boost_curvature
92 ));
93 text.push_str(&format!(
94 "(R/F) High-pass frequency: {:.2}\n",
95 bloom.high_pass_frequency
96 ));
97 text.push_str(&format!(
98 "(T/G) Mode: {}\n",
99 match bloom.composite_mode {
100 BloomCompositeMode::EnergyConserving => "Energy-conserving",
101 BloomCompositeMode::Additive => "Additive",
102 }
103 ));
104 text.push_str(&format!(
105 "(Y/H) Threshold: {:.2}\n",
106 bloom.prefilter.threshold
107 ));
108 text.push_str(&format!(
109 "(U/J) Threshold softness: {:.2}\n",
110 bloom.prefilter.threshold_softness
111 ));
112 text.push_str(&format!("(I/K) Horizontal Scale: {:.2}\n", bloom.scale.x));
113
114 if keycode.just_pressed(KeyCode::Space) {
115 commands.entity(camera_entity).remove::<Bloom>();
116 }
117
118 let dt = time.delta_secs();
119
120 if keycode.pressed(KeyCode::KeyA) {
121 bloom.intensity -= dt / 10.0;
122 }
123 if keycode.pressed(KeyCode::KeyQ) {
124 bloom.intensity += dt / 10.0;
125 }
126 bloom.intensity = bloom.intensity.clamp(0.0, 1.0);
127
128 if keycode.pressed(KeyCode::KeyS) {
129 bloom.low_frequency_boost -= dt / 10.0;
130 }
131 if keycode.pressed(KeyCode::KeyW) {
132 bloom.low_frequency_boost += dt / 10.0;
133 }
134 bloom.low_frequency_boost = bloom.low_frequency_boost.clamp(0.0, 1.0);
135
136 if keycode.pressed(KeyCode::KeyD) {
137 bloom.low_frequency_boost_curvature -= dt / 10.0;
138 }
139 if keycode.pressed(KeyCode::KeyE) {
140 bloom.low_frequency_boost_curvature += dt / 10.0;
141 }
142 bloom.low_frequency_boost_curvature =
143 bloom.low_frequency_boost_curvature.clamp(0.0, 1.0);
144
145 if keycode.pressed(KeyCode::KeyF) {
146 bloom.high_pass_frequency -= dt / 10.0;
147 }
148 if keycode.pressed(KeyCode::KeyR) {
149 bloom.high_pass_frequency += dt / 10.0;
150 }
151 bloom.high_pass_frequency = bloom.high_pass_frequency.clamp(0.0, 1.0);
152
153 if keycode.pressed(KeyCode::KeyG) {
154 bloom.composite_mode = BloomCompositeMode::Additive;
155 }
156 if keycode.pressed(KeyCode::KeyT) {
157 bloom.composite_mode = BloomCompositeMode::EnergyConserving;
158 }
159
160 if keycode.pressed(KeyCode::KeyH) {
161 bloom.prefilter.threshold -= dt;
162 }
163 if keycode.pressed(KeyCode::KeyY) {
164 bloom.prefilter.threshold += dt;
165 }
166 bloom.prefilter.threshold = bloom.prefilter.threshold.max(0.0);
167
168 if keycode.pressed(KeyCode::KeyJ) {
169 bloom.prefilter.threshold_softness -= dt / 10.0;
170 }
171 if keycode.pressed(KeyCode::KeyU) {
172 bloom.prefilter.threshold_softness += dt / 10.0;
173 }
174 bloom.prefilter.threshold_softness = bloom.prefilter.threshold_softness.clamp(0.0, 1.0);
175
176 if keycode.pressed(KeyCode::KeyK) {
177 bloom.scale.x -= dt * 2.0;
178 }
179 if keycode.pressed(KeyCode::KeyI) {
180 bloom.scale.x += dt * 2.0;
181 }
182 bloom.scale.x = bloom.scale.x.clamp(0.0, 16.0);
183 }
184
185 None => {
186 text.0 = "Bloom: Off (Toggle: Space)\n".to_string();
187
188 if keycode.just_pressed(KeyCode::Space) {
189 commands.entity(camera_entity).insert(Bloom::default());
190 }
191 }
192 }
193
194 text.push_str(&format!("(O) Tonemapping: {tonemapping:?}\n"));
195 if keycode.just_pressed(KeyCode::KeyO) {
196 commands
197 .entity(camera_entity)
198 .insert(next_tonemap(tonemapping));
199 }
200}22fn setup(
23 mut commands: Commands,
24 mut meshes: ResMut<Assets<Mesh>>,
25 mut materials: ResMut<Assets<StandardMaterial>>,
26 mut animations: ResMut<Assets<AnimationClip>>,
27 mut graphs: ResMut<Assets<AnimationGraph>>,
28) {
29 // Camera
30 commands.spawn((
31 Camera3d::default(),
32 Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
33 ));
34
35 // Light
36 commands.spawn((
37 PointLight {
38 intensity: 500_000.0,
39 ..default()
40 },
41 Transform::from_xyz(0.0, 2.5, 0.0),
42 ));
43
44 // Let's use the `Name` component to target entities. We can use anything we
45 // like, but names are convenient.
46 let planet = Name::new("planet");
47 let orbit_controller = Name::new("orbit_controller");
48 let satellite = Name::new("satellite");
49
50 // Creating the animation
51 let mut animation = AnimationClip::default();
52 // A curve can modify a single part of a transform: here, the translation.
53 let planet_animation_target_id = AnimationTargetId::from_name(&planet);
54 animation.add_curve_to_target(
55 planet_animation_target_id,
56 AnimatableCurve::new(
57 animated_field!(Transform::translation),
58 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
59 Vec3::new(1.0, 0.0, 1.0),
60 Vec3::new(-1.0, 0.0, 1.0),
61 Vec3::new(-1.0, 0.0, -1.0),
62 Vec3::new(1.0, 0.0, -1.0),
63 // in case seamless looping is wanted, the last keyframe should
64 // be the same as the first one
65 Vec3::new(1.0, 0.0, 1.0),
66 ]))
67 .expect("should be able to build translation curve because we pass in valid samples"),
68 ),
69 );
70 // Or it can modify the rotation of the transform.
71 // To find the entity to modify, the hierarchy will be traversed looking for
72 // an entity with the right name at each level.
73 let orbit_controller_animation_target_id =
74 AnimationTargetId::from_names([planet.clone(), orbit_controller.clone()].iter());
75 animation.add_curve_to_target(
76 orbit_controller_animation_target_id,
77 AnimatableCurve::new(
78 animated_field!(Transform::rotation),
79 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
80 Quat::IDENTITY,
81 Quat::from_axis_angle(Vec3::Y, PI / 2.),
82 Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
83 Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
84 Quat::IDENTITY,
85 ]))
86 .expect("Failed to build rotation curve"),
87 ),
88 );
89 // If a curve in an animation is shorter than the other, it will not repeat
90 // until all other curves are finished. In that case, another animation should
91 // be created for each part that would have a different duration / period.
92 let satellite_animation_target_id = AnimationTargetId::from_names(
93 [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
94 );
95 animation.add_curve_to_target(
96 satellite_animation_target_id,
97 AnimatableCurve::new(
98 animated_field!(Transform::scale),
99 UnevenSampleAutoCurve::new(
100 [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
101 .into_iter()
102 .zip([
103 Vec3::splat(0.8),
104 Vec3::splat(1.2),
105 Vec3::splat(0.8),
106 Vec3::splat(1.2),
107 Vec3::splat(0.8),
108 Vec3::splat(1.2),
109 Vec3::splat(0.8),
110 Vec3::splat(1.2),
111 Vec3::splat(0.8),
112 ]),
113 )
114 .expect("Failed to build scale curve"),
115 ),
116 );
117 // There can be more than one curve targeting the same entity path.
118 animation.add_curve_to_target(
119 AnimationTargetId::from_names(
120 [planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
121 ),
122 AnimatableCurve::new(
123 animated_field!(Transform::rotation),
124 UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
125 Quat::IDENTITY,
126 Quat::from_axis_angle(Vec3::Y, PI / 2.),
127 Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
128 Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
129 Quat::IDENTITY,
130 ]))
131 .expect("should be able to build translation curve because we pass in valid samples"),
132 ),
133 );
134
135 // Create the animation graph
136 let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));
137
138 // Create the animation player, and set it to repeat
139 let mut player = AnimationPlayer::default();
140 player.play(animation_index).repeat();
141
142 // Create the scene that will be animated
143 // First entity is the planet
144 let planet_entity = commands
145 .spawn((
146 Mesh3d(meshes.add(Sphere::default())),
147 MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
148 // Add the animation graph and player
149 planet,
150 AnimationGraphHandle(graphs.add(graph)),
151 player,
152 ))
153 .id();
154 commands.entity(planet_entity).insert((
155 planet_animation_target_id,
156 AnimatedBy(planet_entity),
157 children![(
158 Transform::default(),
159 Visibility::default(),
160 orbit_controller,
161 orbit_controller_animation_target_id,
162 AnimatedBy(planet_entity),
163 children![(
164 Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
165 MeshMaterial3d(materials.add(Color::srgb(0.3, 0.9, 0.3))),
166 Transform::from_xyz(1.5, 0.0, 0.0),
167 satellite_animation_target_id,
168 AnimatedBy(planet_entity),
169 satellite,
170 )],
171 )],
172 ));
173}Sourcepub fn insert_if<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn insert_if<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity if the predicate returns true.
This is useful for chaining method calls.
§Example
#[derive(Component)]
struct StillLoadingStats;
#[derive(Component)]
struct Health(u32);
fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
.insert_if(Health(10), || !player.is_spectator())
.remove::<StillLoadingStats>();
}Sourcepub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity without overwriting.
This is the same as EntityCommands::insert, but in case of duplicate
components will leave the old values instead of replacing them with new ones.
See also entry, which lets you modify a Component if it’s present,
as well as initialize it with a default value.
Sourcepub fn insert_if_new_and<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn insert_if_new_and<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity without overwriting if the
predicate returns true.
This is the same as EntityCommands::insert_if, but in case of duplicate
components will leave the old values instead of replacing them with new ones.
Sourcepub unsafe fn insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
pub unsafe fn insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
Adds a dynamic Component to the entity.
This will overwrite any previous value(s) of the same component type.
You should prefer to use the typed API EntityCommands::insert where possible.
§Safety
ComponentIdmust be from the same world asself.Tmust have the same layout as the one passed duringcomponent_idcreation.
Sourcepub unsafe fn try_insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
pub unsafe fn try_insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
Adds a dynamic Component to the entity.
This will overwrite any previous value(s) of the same component type.
You should prefer to use the typed API EntityCommands::try_insert where possible.
§Note
If the entity does not exist when this command is executed, the resulting error will be ignored.
§Safety
ComponentIdmust be from the same world asself.Tmust have the same layout as the one passed duringcomponent_idcreation.
Sourcepub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity.
This will overwrite any previous value(s) of the same component type.
§Note
If the entity does not exist when this command is executed, the resulting error will be ignored.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands.entity(player.entity)
// You can insert individual components:
.try_insert(Defense(10))
// You can also insert tuples of components:
.try_insert(CombatBundle {
health: Health(100),
strength: Strength(40),
});
// Suppose this occurs in a parallel adjacent system or process.
commands.entity(player.entity).despawn();
// This will not panic nor will it add the component.
commands.entity(player.entity).try_insert(Defense(5));
}Sourcepub fn try_insert_if<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn try_insert_if<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Sourcepub fn try_insert_if_new_and<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn try_insert_if_new_and<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity without overwriting if the
predicate returns true.
This is the same as EntityCommands::try_insert_if, but in case of duplicate
components will leave the old values instead of replacing them with new ones.
§Note
If the entity does not exist when this command is executed, the resulting error will be ignored.
Sourcepub fn try_insert_if_new(
&mut self,
bundle: impl Bundle,
) -> &mut EntityCommands<'a>
pub fn try_insert_if_new( &mut self, bundle: impl Bundle, ) -> &mut EntityCommands<'a>
Adds a Bundle of components to the entity without overwriting.
This is the same as EntityCommands::try_insert, but in case of duplicate
components will leave the old values instead of replacing them with new ones.
§Note
If the entity does not exist when this command is executed, the resulting error will be ignored.
Sourcepub fn remove<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn remove<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
Removes a Bundle of components from the entity.
This will remove all components that intersect with the provided bundle; the entity does not need to have all the components in the bundle.
This will emit a warning if the entity does not exist.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can remove individual components:
.remove::<Defense>()
// You can also remove pre-defined bundles of components:
.remove::<CombatBundle>()
// You can also remove tuples of components and bundles.
// This is equivalent to the calls above:
.remove::<(Defense, CombatBundle)>();
}Examples found in repository?
More examples
31fn screenshot_saving(
32 mut commands: Commands,
33 screenshot_saving: Query<Entity, With<Capturing>>,
34 window: Single<Entity, With<Window>>,
35) {
36 match screenshot_saving.iter().count() {
37 0 => {
38 commands.entity(*window).remove::<CursorIcon>();
39 }
40 x if x > 0 => {
41 commands
42 .entity(*window)
43 .insert(CursorIcon::from(SystemCursorIcon::Progress));
44 }
45 _ => {}
46 }
47}48fn focus_system(
49 mut commands: Commands,
50 focus: Res<InputFocus>,
51 mut query: Query<Entity, With<Button>>,
52) {
53 if focus.is_changed() {
54 for button in query.iter_mut() {
55 if focus.0 == Some(button) {
56 commands.entity(button).insert(Outline {
57 color: Color::WHITE,
58 width: px(2),
59 offset: px(2),
60 });
61 } else {
62 commands.entity(button).remove::<Outline>();
63 }
64 }
65 }
66}72fn update_bloom_settings(
73 camera: Single<(Entity, &Tonemapping, Option<&mut Bloom>), With<Camera>>,
74 mut text: Single<&mut Text>,
75 mut commands: Commands,
76 keycode: Res<ButtonInput<KeyCode>>,
77 time: Res<Time>,
78) {
79 let (camera_entity, tonemapping, bloom) = camera.into_inner();
80
81 match bloom {
82 Some(mut bloom) => {
83 text.0 = "Bloom (Toggle: Space)\n".to_string();
84 text.push_str(&format!("(Q/A) Intensity: {:.2}\n", bloom.intensity));
85 text.push_str(&format!(
86 "(W/S) Low-frequency boost: {:.2}\n",
87 bloom.low_frequency_boost
88 ));
89 text.push_str(&format!(
90 "(E/D) Low-frequency boost curvature: {:.2}\n",
91 bloom.low_frequency_boost_curvature
92 ));
93 text.push_str(&format!(
94 "(R/F) High-pass frequency: {:.2}\n",
95 bloom.high_pass_frequency
96 ));
97 text.push_str(&format!(
98 "(T/G) Mode: {}\n",
99 match bloom.composite_mode {
100 BloomCompositeMode::EnergyConserving => "Energy-conserving",
101 BloomCompositeMode::Additive => "Additive",
102 }
103 ));
104 text.push_str(&format!(
105 "(Y/H) Threshold: {:.2}\n",
106 bloom.prefilter.threshold
107 ));
108 text.push_str(&format!(
109 "(U/J) Threshold softness: {:.2}\n",
110 bloom.prefilter.threshold_softness
111 ));
112 text.push_str(&format!("(I/K) Horizontal Scale: {:.2}\n", bloom.scale.x));
113
114 if keycode.just_pressed(KeyCode::Space) {
115 commands.entity(camera_entity).remove::<Bloom>();
116 }
117
118 let dt = time.delta_secs();
119
120 if keycode.pressed(KeyCode::KeyA) {
121 bloom.intensity -= dt / 10.0;
122 }
123 if keycode.pressed(KeyCode::KeyQ) {
124 bloom.intensity += dt / 10.0;
125 }
126 bloom.intensity = bloom.intensity.clamp(0.0, 1.0);
127
128 if keycode.pressed(KeyCode::KeyS) {
129 bloom.low_frequency_boost -= dt / 10.0;
130 }
131 if keycode.pressed(KeyCode::KeyW) {
132 bloom.low_frequency_boost += dt / 10.0;
133 }
134 bloom.low_frequency_boost = bloom.low_frequency_boost.clamp(0.0, 1.0);
135
136 if keycode.pressed(KeyCode::KeyD) {
137 bloom.low_frequency_boost_curvature -= dt / 10.0;
138 }
139 if keycode.pressed(KeyCode::KeyE) {
140 bloom.low_frequency_boost_curvature += dt / 10.0;
141 }
142 bloom.low_frequency_boost_curvature =
143 bloom.low_frequency_boost_curvature.clamp(0.0, 1.0);
144
145 if keycode.pressed(KeyCode::KeyF) {
146 bloom.high_pass_frequency -= dt / 10.0;
147 }
148 if keycode.pressed(KeyCode::KeyR) {
149 bloom.high_pass_frequency += dt / 10.0;
150 }
151 bloom.high_pass_frequency = bloom.high_pass_frequency.clamp(0.0, 1.0);
152
153 if keycode.pressed(KeyCode::KeyG) {
154 bloom.composite_mode = BloomCompositeMode::Additive;
155 }
156 if keycode.pressed(KeyCode::KeyT) {
157 bloom.composite_mode = BloomCompositeMode::EnergyConserving;
158 }
159
160 if keycode.pressed(KeyCode::KeyH) {
161 bloom.prefilter.threshold -= dt;
162 }
163 if keycode.pressed(KeyCode::KeyY) {
164 bloom.prefilter.threshold += dt;
165 }
166 bloom.prefilter.threshold = bloom.prefilter.threshold.max(0.0);
167
168 if keycode.pressed(KeyCode::KeyJ) {
169 bloom.prefilter.threshold_softness -= dt / 10.0;
170 }
171 if keycode.pressed(KeyCode::KeyU) {
172 bloom.prefilter.threshold_softness += dt / 10.0;
173 }
174 bloom.prefilter.threshold_softness = bloom.prefilter.threshold_softness.clamp(0.0, 1.0);
175
176 if keycode.pressed(KeyCode::KeyK) {
177 bloom.scale.x -= dt * 2.0;
178 }
179 if keycode.pressed(KeyCode::KeyI) {
180 bloom.scale.x += dt * 2.0;
181 }
182 bloom.scale.x = bloom.scale.x.clamp(0.0, 16.0);
183 }
184
185 None => {
186 text.0 = "Bloom: Off (Toggle: Space)\n".to_string();
187
188 if keycode.just_pressed(KeyCode::Space) {
189 commands.entity(camera_entity).insert(Bloom::default());
190 }
191 }
192 }
193
194 text.push_str(&format!("(O) Tonemapping: {tonemapping:?}\n"));
195 if keycode.just_pressed(KeyCode::KeyO) {
196 commands
197 .entity(camera_entity)
198 .insert(next_tonemap(tonemapping));
199 }
200}Sourcepub fn remove_if<B>(
&mut self,
condition: impl FnOnce() -> bool,
) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn remove_if<B>(
&mut self,
condition: impl FnOnce() -> bool,
) -> &mut EntityCommands<'a>where
B: Bundle,
Removes a Bundle of components from the entity if the predicate returns true.
This is useful for chaining method calls.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
.remove_if::<(Defense, CombatBundle)>(|| !player.is_spectator());
}Sourcepub fn try_remove_if<B>(
&mut self,
condition: impl FnOnce() -> bool,
) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn try_remove_if<B>(
&mut self,
condition: impl FnOnce() -> bool,
) -> &mut EntityCommands<'a>where
B: Bundle,
Sourcepub fn try_remove<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn try_remove<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
Removes a Bundle of components from the entity.
This will remove all components that intersect with the provided bundle; the entity does not need to have all the components in the bundle.
Unlike Self::remove,
this will not emit a warning if the entity does not exist.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can remove individual components:
.try_remove::<Defense>()
// You can also remove pre-defined bundles of components:
.try_remove::<CombatBundle>()
// You can also remove tuples of components and bundles.
// This is equivalent to the calls above:
.try_remove::<(Defense, CombatBundle)>();
}Sourcepub fn remove_with_requires<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn remove_with_requires<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
Removes a Bundle of components from the entity,
and also removes any components required by the components in the bundle.
This will remove all components that intersect with the provided bundle; the entity does not need to have all the components in the bundle.
§Example
#[derive(Component)]
#[require(B)]
struct A;
#[derive(Component, Default)]
struct B;
fn remove_with_requires_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// Removes both A and B from the entity, because B is required by A.
.remove_with_requires::<A>();
}Sourcepub fn remove_by_id(
&mut self,
component_id: ComponentId,
) -> &mut EntityCommands<'a>
pub fn remove_by_id( &mut self, component_id: ComponentId, ) -> &mut EntityCommands<'a>
Removes a dynamic Component from the entity if it exists.
§Panics
Panics if the provided ComponentId does not exist in the World.
Sourcepub fn clear(&mut self) -> &mut EntityCommands<'a>
pub fn clear(&mut self) -> &mut EntityCommands<'a>
Removes all components associated with the entity.
Sourcepub fn despawn(&mut self)
pub fn despawn(&mut self)
Despawns the entity.
This will emit a warning if the entity does not exist.
§Note
This will also despawn the entities in any RelationshipTarget
that is configured to despawn descendants.
For example, this will recursively despawn Children.
§Example
fn remove_character_system(
mut commands: Commands,
character_to_remove: Res<CharacterToRemove>
) {
commands.entity(character_to_remove.entity).despawn();
}Examples found in repository?
138fn on_drag_drop(
139 mut event: On<Pointer<DragDrop>>,
140 button: Single<Entity, With<DraggableButton>>,
141 mut commands: Commands,
142 ghost: Single<Entity, With<GhostPreview>>,
143 mut meshes: ResMut<Assets<Mesh>>,
144 mut materials: ResMut<Assets<ColorMaterial>>,
145) {
146 if event.dropped == *button {
147 commands.entity(*ghost).despawn();
148 let Some(position) = event.hit.position else {
149 return;
150 };
151 commands.spawn((
152 DroppedElement,
153 Mesh2d(meshes.add(Circle::new(ELEMENT_SIZE))),
154 MeshMaterial2d(materials.add(Color::srgb(1.0, 1.0, 0.6))),
155 Transform::from_translation(position + 2. * Vec3::Z),
156 Pickable::IGNORE,
157 ));
158 event.propagate(false);
159 }
160}
161
162fn on_drag_leave(
163 mut event: On<Pointer<DragLeave>>,
164 button: Single<Entity, With<DraggableButton>>,
165 mut commands: Commands,
166 ghost: Single<Entity, With<GhostPreview>>,
167) {
168 if event.dragged == *button {
169 commands.entity(*ghost).despawn();
170 event.propagate(false);
171 }
172}Sourcepub fn try_despawn(&mut self)
pub fn try_despawn(&mut self)
Despawns the entity.
Unlike Self::despawn,
this will not emit a warning if the entity does not exist.
§Note
This will also despawn the entities in any RelationshipTarget
that is configured to despawn descendants.
For example, this will recursively despawn Children.
Sourcepub fn queue<C, T, M>(&mut self, command: C) -> &mut EntityCommands<'a>where
C: EntityCommand<T> + CommandWithEntity<M>,
pub fn queue<C, T, M>(&mut self, command: C) -> &mut EntityCommands<'a>where
C: EntityCommand<T> + CommandWithEntity<M>,
Pushes an EntityCommand to the queue,
which will get executed for the current Entity.
The default error handler
will be used to handle error cases.
Every EntityCommand checks whether the entity exists at the time of execution
and returns an error if it does not.
To use a custom error handler, see EntityCommands::queue_handled.
The command can be:
- A custom struct that implements
EntityCommand. - A closure or function that matches the following signature:
- A built-in command from the
entity_commandmodule.
§Example
commands
.spawn_empty()
// Closures with this signature implement `EntityCommand`.
.queue(|entity: EntityWorldMut| {
println!("Executed an EntityCommand for {}", entity.id());
});Sourcepub fn queue_handled<C, T, M>(
&mut self,
command: C,
error_handler: fn(BevyError, ErrorContext),
) -> &mut EntityCommands<'a>where
C: EntityCommand<T> + CommandWithEntity<M>,
pub fn queue_handled<C, T, M>(
&mut self,
command: C,
error_handler: fn(BevyError, ErrorContext),
) -> &mut EntityCommands<'a>where
C: EntityCommand<T> + CommandWithEntity<M>,
Pushes an EntityCommand to the queue,
which will get executed for the current Entity.
The given error_handler will be used to handle error cases.
Every EntityCommand checks whether the entity exists at the time of execution
and returns an error if it does not.
To implicitly use the default error handler, see EntityCommands::queue.
The command can be:
- A custom struct that implements
EntityCommand. - A closure or function that matches the following signature:
- A built-in command from the
entity_commandmodule.
§Example
use bevy_ecs::error::warn;
commands
.spawn_empty()
// Closures with this signature implement `EntityCommand`.
.queue_handled(
|entity: EntityWorldMut| -> Result {
let value: usize = "100".parse()?;
println!("Successfully parsed the value {} for entity {}", value, entity.id());
Ok(())
},
warn
);Sourcepub fn queue_silenced<C, T, M>(&mut self, command: C) -> &mut EntityCommands<'a>where
C: EntityCommand<T> + CommandWithEntity<M>,
pub fn queue_silenced<C, T, M>(&mut self, command: C) -> &mut EntityCommands<'a>where
C: EntityCommand<T> + CommandWithEntity<M>,
Pushes an EntityCommand to the queue, which will get executed for the current Entity.
Unlike EntityCommands::queue_handled, this will completely ignore any errors that occur.
Sourcepub fn retain<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn retain<B>(&mut self) -> &mut EntityCommands<'a>where
B: Bundle,
Removes all components except the given Bundle from the entity.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can retain a pre-defined Bundle of components,
// with this removing only the Defense component.
.retain::<CombatBundle>()
// You can also retain only a single component.
.retain::<Health>();
}Sourcepub fn log_components(&mut self) -> &mut EntityCommands<'a>
pub fn log_components(&mut self) -> &mut EntityCommands<'a>
Logs the components of the entity at the info level.
Sourcepub fn commands_mut(&mut self) -> &mut Commands<'a, 'a>
pub fn commands_mut(&mut self) -> &mut Commands<'a, 'a>
Returns a mutable reference to the underlying Commands.
Sourcepub fn observe<E, B, M>(
&mut self,
observer: impl IntoObserverSystem<E, B, M>,
) -> &mut EntityCommands<'a>where
E: EntityEvent,
B: Bundle,
pub fn observe<E, B, M>(
&mut self,
observer: impl IntoObserverSystem<E, B, M>,
) -> &mut EntityCommands<'a>where
E: EntityEvent,
B: Bundle,
Creates an Observer watching for an EntityEvent of type E whose EntityEvent::event_target
targets this entity.
Examples found in repository?
17fn screenshot_on_spacebar(
18 mut commands: Commands,
19 input: Res<ButtonInput<KeyCode>>,
20 mut counter: Local<u32>,
21) {
22 if input.just_pressed(KeyCode::Space) {
23 let path = format!("./screenshot-{}.png", *counter);
24 *counter += 1;
25 commands
26 .spawn(Screenshot::primary_window())
27 .observe(save_to_disk(path));
28 }
29}More examples
29fn setup(
30 mut commands: Commands,
31 mut meshes: ResMut<Assets<Mesh>>,
32 mut materials: ResMut<Assets<ColorMaterial>>,
33) {
34 commands.spawn(Camera2d);
35
36 commands
37 .spawn((
38 Node {
39 width: Val::Percent(100.0),
40 height: Val::Percent(100.0),
41 align_items: AlignItems::Center,
42 justify_content: JustifyContent::Start,
43 ..default()
44 },
45 Pickable::IGNORE,
46 ))
47 .with_children(|parent| {
48 parent
49 .spawn((
50 DraggableButton,
51 Node {
52 width: Val::Px(BUTTON_WIDTH),
53 height: Val::Px(BUTTON_HEIGHT),
54 margin: UiRect::all(Val::Px(10.0)),
55 justify_content: JustifyContent::Center,
56 align_items: AlignItems::Center,
57 ..default()
58 },
59 BackgroundColor(Color::srgb(1.0, 0.0, 0.0)),
60 ))
61 .with_child((
62 Text::new("Drag from me"),
63 TextColor(Color::WHITE),
64 Pickable::IGNORE,
65 ))
66 .observe(
67 |mut event: On<Pointer<DragStart>>,
68 mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| {
69 button_color.0 = Color::srgb(1.0, 0.5, 0.0);
70 event.propagate(false);
71 },
72 )
73 .observe(
74 |mut event: On<Pointer<DragEnd>>,
75 mut button_color: Single<&mut BackgroundColor, With<DraggableButton>>| {
76 button_color.0 = Color::srgb(1.0, 0.0, 0.0);
77 event.propagate(false);
78 },
79 );
80 });
81
82 commands
83 .spawn((
84 DropArea,
85 Mesh2d(meshes.add(Rectangle::new(AREA_SIZE, AREA_SIZE))),
86 MeshMaterial2d(materials.add(Color::srgb(0.1, 0.4, 0.1))),
87 Transform::IDENTITY,
88 children![(
89 Text2d::new("Drop here"),
90 TextFont::from_font_size(50.),
91 TextColor(Color::BLACK),
92 Pickable::IGNORE,
93 Transform::from_translation(Vec3::Z),
94 )],
95 ))
96 .observe(on_drag_enter)
97 .observe(on_drag_over)
98 .observe(on_drag_drop)
99 .observe(on_drag_leave);
100}68fn setup(mut commands: Commands) {
69 // ui camera
70 commands.spawn(Camera2d);
71 commands
72 .spawn(Node {
73 width: percent(100),
74 height: percent(100),
75 display: Display::Flex,
76 flex_direction: FlexDirection::Column,
77 align_items: AlignItems::Center,
78 justify_content: JustifyContent::Center,
79 row_gap: px(6),
80 ..default()
81 })
82 .observe(
83 |mut event: On<Pointer<Click>>, mut focus: ResMut<InputFocus>| {
84 focus.0 = None;
85 event.propagate(false);
86 },
87 )
88 .with_children(|parent| {
89 for (label, tab_group, indices) in [
90 // In this group all the buttons have the same `TabIndex` so they will be visited according to their order as children.
91 ("TabGroup 0", TabGroup::new(0), [0, 0, 0, 0]),
92 // In this group the `TabIndex`s are reversed so the buttons will be visited in right-to-left order.
93 ("TabGroup 2", TabGroup::new(2), [3, 2, 1, 0]),
94 // In this group the orders of the indices and buttons match so the buttons will be visited in left-to-right order.
95 ("TabGroup 1", TabGroup::new(1), [0, 1, 2, 3]),
96 // Visit the modal group's buttons in an arbitrary order.
97 ("Modal TabGroup", TabGroup::modal(), [0, 3, 1, 2]),
98 ] {
99 parent.spawn(Text::new(label));
100 parent
101 .spawn((
102 Node {
103 display: Display::Flex,
104 flex_direction: FlexDirection::Row,
105 column_gap: px(6),
106 margin: UiRect {
107 bottom: px(10),
108 ..default()
109 },
110 ..default()
111 },
112 tab_group,
113 ))
114 .with_children(|parent| {
115 for i in indices {
116 parent
117 .spawn((
118 Button,
119 Node {
120 width: px(200),
121 height: px(65),
122 border: UiRect::all(px(5)),
123 justify_content: JustifyContent::Center,
124 align_items: AlignItems::Center,
125 ..default()
126 },
127 BorderColor::all(Color::BLACK),
128 BackgroundColor(NORMAL_BUTTON),
129 TabIndex(i),
130 children![(
131 Text::new(format!("TabIndex {i}")),
132 TextFont {
133 font_size: 20.0,
134 ..default()
135 },
136 TextColor(Color::srgb(0.9, 0.9, 0.9)),
137 )],
138 ))
139 .observe(
140 |mut click: On<Pointer<Click>>,
141 mut focus: ResMut<InputFocus>| {
142 focus.0 = Some(click.entity);
143 click.propagate(false);
144 },
145 );
146 }
147 });
148 }
149 });
150}16fn setup(mut commands: Commands) {
17 commands.spawn(Camera2d);
18 commands
19 .spawn((Node {
20 display: Display::Grid,
21 align_self: AlignSelf::Center,
22 justify_self: JustifySelf::Center,
23 ..Default::default()
24 }, Pickable::IGNORE, BackgroundColor(Color::srgb(0.4, 0.4, 0.4))))
25 .with_children(|parent| {
26 let tile_colors = [
27 Color::srgb(0.2, 0.2, 0.8),
28 Color::srgb(0.8, 0.2, 0.2)
29 ];
30 for column in 0..COLUMNS {
31 for row in 0..ROWS {
32 let i = column + row * COLUMNS;
33 let tile_color = tile_colors[((row % 2) + column) as usize % tile_colors.len()];
34 let tile_border_color = tile_color.darker(0.025);
35 parent
36 .spawn((
37 Node {
38 width: Val::Px(TILE_SIZE),
39 height: Val::Px(TILE_SIZE),
40 border: UiRect::all(Val::Px(4.)),
41 grid_row: GridPlacement::start(row + 1),
42 grid_column: GridPlacement::start(column + 1),
43 align_items: AlignItems::Center,
44 justify_content: JustifyContent::Center,
45 ..Default::default()
46 },
47 BorderColor::all(tile_border_color),
48 BackgroundColor(tile_color),
49 Outline {
50 width: Val::Px(2.),
51 offset: Val::ZERO,
52 color: Color::NONE,
53 },
54 Pickable {
55 should_block_lower: false,
56 is_hoverable: true,
57 },
58 GlobalZIndex::default()
59 ))
60 .observe(move |on_over: On<Pointer<Over>>, mut query: Query<(&mut BackgroundColor, &mut BorderColor)>| {
61 if let Ok((mut background_color, mut border_color)) = query.get_mut(on_over.event_target()) {
62 background_color.0 = tile_color.lighter(0.1);
63 border_color.set_all(tile_border_color.lighter(0.1));
64 }
65 })
66 .observe(move |on_out: On<Pointer<Out>>, mut query: Query<(&mut BackgroundColor, &mut BorderColor)>| {
67 if let Ok((mut background_color, mut border_color)) = query.get_mut(on_out.event_target()) {
68 background_color.0 = tile_color;
69 border_color.set_all(tile_border_color);
70 }
71 })
72 .observe(|on_drag_start: On<Pointer<DragStart>>, mut query: Query<(&mut Outline, &mut GlobalZIndex)>| {
73 if let Ok((mut outline, mut global_zindex, )) = query.get_mut(on_drag_start.event_target()) {
74 outline.color = Color::WHITE;
75 global_zindex.0 = 1;
76 }
77 })
78 .observe(|on_drag: On<Pointer<Drag>>, mut query: Query<&mut UiTransform>| {
79 if let Ok(mut transform) = query.get_mut(on_drag.event_target()) {
80 transform.translation = Val2::px(on_drag.distance.x, on_drag.distance.y);
81 }
82 })
83 .observe(move |on_drag_end: On<Pointer<DragEnd>>, mut query: Query<(&mut UiTransform, &mut Outline, &mut GlobalZIndex)>| {
84 if let Ok((mut transform, mut outline, mut global_zindex)) = query.get_mut(on_drag_end.event_target()) {
85 transform.translation = Val2::ZERO;
86 outline.color = Color::NONE;
87 global_zindex.0 = 0;
88 }
89 })
90 .observe(|on_drag_drop: On<Pointer<DragDrop>>, mut query: Query<&mut Node>| {
91 if let Ok([mut a, mut b]) = query.get_many_mut([on_drag_drop.event_target(), on_drag_drop.dropped]) {
92 core::mem::swap(&mut a.grid_row, &mut b.grid_row);
93 core::mem::swap(&mut a.grid_column, &mut b.grid_column);
94 }
95 })
96 .with_child((Text::new(format!("{i}")), Pickable::IGNORE));
97 }
98 }
99 });
100}Sourcepub fn clone_with_opt_out(
&mut self,
target: Entity,
config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static,
) -> &mut EntityCommands<'a>
pub fn clone_with_opt_out( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static, ) -> &mut EntityCommands<'a>
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.
§Panics
The command will panic when applied if the target entity does not exist.
§Example
Configure through EntityClonerBuilder<OptOut> as follows:
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);
fn example_system(mut commands: Commands) {
// Create an empty entity.
let target = commands.spawn_empty().id();
// Create a new entity and keep its EntityCommands.
let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
// Clone ComponentA but not ComponentB onto the target.
entity.clone_with_opt_out(target, |builder| {
builder.deny::<ComponentB>();
});
}See EntityClonerBuilder for more options.
Sourcepub fn clone_with_opt_in(
&mut self,
target: Entity,
config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static,
) -> &mut EntityCommands<'a>
pub fn clone_with_opt_in( &mut self, target: Entity, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static, ) -> &mut EntityCommands<'a>
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.
§Panics
The command will panic when applied if the target entity does not exist.
§Example
Configure through EntityClonerBuilder<OptIn> as follows:
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);
fn example_system(mut commands: Commands) {
// Create an empty entity.
let target = commands.spawn_empty().id();
// Create a new entity and keep its EntityCommands.
let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
// Clone ComponentA but not ComponentB onto the target.
entity.clone_with_opt_in(target, |builder| {
builder.allow::<ComponentA>();
});
}See EntityClonerBuilder for more options.
Sourcepub fn clone_and_spawn(&mut self) -> EntityCommands<'_>
pub fn clone_and_spawn(&mut self) -> EntityCommands<'_>
Spawns a clone of this entity and returns the EntityCommands 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 EntityCommands::clone_and_spawn_with_opt_out/
opt_out.
§Note
If the original entity does not exist when this command is applied, the returned entity will have no components.
§Example
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);
fn example_system(mut commands: Commands) {
// Create a new entity and store its EntityCommands.
let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
// Create a clone of the entity.
let mut entity_clone = entity.clone_and_spawn();
}Sourcepub fn clone_and_spawn_with_opt_out(
&mut self,
config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static,
) -> EntityCommands<'_>
pub fn clone_and_spawn_with_opt_out( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptOut>) + Send + Sync + 'static, ) -> EntityCommands<'_>
Spawns a clone of this entity and allows configuring cloning behavior
using EntityClonerBuilder, returning the EntityCommands 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.
See the methods on EntityClonerBuilder<OptOut> for more options.
§Note
If the original entity does not exist when this command is applied, the returned entity will have no components.
§Example
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);
fn example_system(mut commands: Commands) {
// Create a new entity and store its EntityCommands.
let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
// Create a clone of the entity with ComponentA but without ComponentB.
let mut entity_clone = entity.clone_and_spawn_with_opt_out(|builder| {
builder.deny::<ComponentB>();
});
}Sourcepub fn clone_and_spawn_with_opt_in(
&mut self,
config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static,
) -> EntityCommands<'_>
pub fn clone_and_spawn_with_opt_in( &mut self, config: impl FnOnce(&mut EntityClonerBuilder<'_, OptIn>) + Send + Sync + 'static, ) -> EntityCommands<'_>
Spawns a clone of this entity and allows configuring cloning behavior
using EntityClonerBuilder, returning the EntityCommands of the clone.
The clone will receive only the components of the original that implement
Clone or Reflect and are
allowed in the config.
See the methods on EntityClonerBuilder<OptIn> for more options.
§Note
If the original entity does not exist when this command is applied, the returned entity will have no components.
§Example
#[derive(Component, Clone)]
struct ComponentA(u32);
#[derive(Component, Clone)]
struct ComponentB(u32);
fn example_system(mut commands: Commands) {
// Create a new entity and store its EntityCommands.
let mut entity = commands.spawn((ComponentA(10), ComponentB(20)));
// Create a clone of the entity with ComponentA but without ComponentB.
let mut entity_clone = entity.clone_and_spawn_with_opt_in(|builder| {
builder.allow::<ComponentA>();
});
}Sourcepub fn clone_components<B>(&mut self, target: Entity) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn clone_components<B>(&mut self, target: Entity) -> &mut EntityCommands<'a>where
B: Bundle,
Sourcepub fn move_components<B>(&mut self, target: Entity) -> &mut EntityCommands<'a>where
B: Bundle,
pub fn move_components<B>(&mut self, target: Entity) -> &mut EntityCommands<'a>where
B: Bundle,
Moves the specified components of this entity into another entity.
Components with Ignore clone behavior will not be moved, while components that
have a Custom clone behavior will be cloned using it and then removed from the source entity.
All other components will be moved without any other special handling.
Note that this will trigger on_remove hooks/observers on this entity and on_insert/on_add hooks/observers on the target entity.
§Panics
The command will panic when applied if the target entity does not exist.
Sourcepub fn trigger<'t, E>(
&mut self,
event_fn: impl FnOnce(Entity) -> E,
) -> &mut EntityCommands<'a>
pub fn trigger<'t, E>( &mut self, event_fn: impl FnOnce(Entity) -> E, ) -> &mut EntityCommands<'a>
Passes the current entity into the given function, and triggers the EntityEvent returned by that function.
§Example
A surprising number of functions meet the trait bounds for event_fn:
#[derive(EntityEvent)]
struct Explode(Entity);
impl From<Entity> for Explode {
fn from(entity: Entity) -> Self {
Explode(entity)
}
}
fn trigger_via_constructor(mut commands: Commands) {
// The fact that `Explode` is a single-field tuple struct
// ensures that `Explode(entity)` is a function that generates
// an EntityEvent, meeting the trait bounds for `event_fn`.
commands.spawn_empty().trigger(Explode);
}
fn trigger_via_from_trait(mut commands: Commands) {
// This variant also works for events like `struct Explode { entity: Entity }`
commands.spawn_empty().trigger(Explode::from);
}
fn trigger_via_closure(mut commands: Commands) {
commands.spawn_empty().trigger(|entity| Explode(entity));
}Trait Implementations§
Source§impl BuildChildrenTransformExt for EntityCommands<'_>
impl BuildChildrenTransformExt for EntityCommands<'_>
Source§fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityCommands<'_>
fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityCommands<'_>
GlobalTransform
by updating its Transform. Read moreSource§fn remove_parent_in_place(&mut self) -> &mut EntityCommands<'_>
fn remove_parent_in_place(&mut self) -> &mut EntityCommands<'_>
GlobalTransform
by updating its Transform to be equal to its current GlobalTransform. Read moreSource§impl ReflectCommandExt for EntityCommands<'_>
impl ReflectCommandExt for EntityCommands<'_>
Source§fn insert_reflect(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut EntityCommands<'_>
fn insert_reflect( &mut self, component: Box<dyn PartialReflect>, ) -> &mut EntityCommands<'_>
AppTypeRegistry. Read moreSource§fn insert_reflect_with_registry<T>(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut EntityCommands<'_>
fn insert_reflect_with_registry<T>( &mut self, component: Box<dyn PartialReflect>, ) -> &mut EntityCommands<'_>
insert_reflect, but using the T resource as type registry instead of
AppTypeRegistry. Read moreSource§fn remove_reflect(
&mut self,
component_type_path: impl Into<Cow<'static, str>>,
) -> &mut EntityCommands<'_>
fn remove_reflect( &mut self, component_type_path: impl Into<Cow<'static, str>>, ) -> &mut EntityCommands<'_>
AppTypeRegistry. Read moreSource§fn remove_reflect_with_registry<T>(
&mut self,
component_type_path: impl Into<Cow<'static, str>>,
) -> &mut EntityCommands<'_>
fn remove_reflect_with_registry<T>( &mut self, component_type_path: impl Into<Cow<'static, str>>, ) -> &mut EntityCommands<'_>
Auto Trait Implementations§
impl<'a> Freeze for EntityCommands<'a>
impl<'a> RefUnwindSafe for EntityCommands<'a>
impl<'a> Send for EntityCommands<'a>
impl<'a> Sync for EntityCommands<'a>
impl<'a> Unpin for EntityCommands<'a>
impl<'a> UnsafeUnpin for EntityCommands<'a>
impl<'a> !UnwindSafe for EntityCommands<'a>
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T ShaderType for self. When used in AsBindGroup
derives, it is safe to assume that all images in self exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
Source§impl<T> Identity for Twhere
T: ?Sized,
impl<T> Identity for Twhere
T: ?Sized,
Source§impl<T> InitializeFromFunction<T> for T
impl<T> InitializeFromFunction<T> for T
Source§fn initialize_from_function(f: fn() -> T) -> T
fn initialize_from_function(f: fn() -> T) -> T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
Source§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
Source§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.Source§impl<Ret> SpawnIfAsync<(), Ret> for Ret
impl<Ret> SpawnIfAsync<(), Ret> for Ret
Source§impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
Source§fn super_from(input: T) -> O
fn super_from(input: T) -> O
Source§impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
Source§fn super_into(self) -> O
fn super_into(self) -> O
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.