Skip to content

Commit 98a08cf

Browse files
committed
feat: remove_component for ReflectComponent (#2682)
# Objective While implementing a plugin for my rollback networking library, I needed to load/save parts of the world. For this, I made a WorldSnapshot that works quite like the current DynamicScene. Using a TypeRegistry to register component types I want to save/load and then using ReflectComponents methods to add or apply components of the given types. However, I noticed there is no method to remove components from entities through the ReflectComponent. ## Solution I added a `remove_component` field to the `ReflectComponent` struct, as well as a `pub fn remove_component(&self, world: &mut World, entity: Entity)` to call that function in `remove_component`. This follows exactly the same pattern all other methods/fields in this struct look like. This is an example how it could be used (at least how I would use it): https://github.com/gschup/bevy_ggrs/blob/6c003f86f1993bcbb21c180fab2e8ef664b7f7c9/src/world_snapshot.rs#L133
1 parent 9d45353 commit 98a08cf

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

crates/bevy_ecs/src/reflect.rs

+8
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use bevy_reflect::{impl_reflect_value, FromType, Reflect, ReflectDeserialize};
1010
pub struct ReflectComponent {
1111
add_component: fn(&mut World, Entity, &dyn Reflect),
1212
apply_component: fn(&mut World, Entity, &dyn Reflect),
13+
remove_component: fn(&mut World, Entity),
1314
reflect_component: fn(&World, Entity) -> Option<&dyn Reflect>,
1415
reflect_component_mut: unsafe fn(&World, Entity) -> Option<ReflectMut>,
1516
copy_component: fn(&World, &mut World, Entity, Entity),
@@ -24,6 +25,10 @@ impl ReflectComponent {
2425
(self.apply_component)(world, entity, component);
2526
}
2627

28+
pub fn remove_component(&self, world: &mut World, entity: Entity) {
29+
(self.remove_component)(world, entity);
30+
}
31+
2732
pub fn reflect_component<'a>(
2833
&self,
2934
world: &'a World,
@@ -83,6 +88,9 @@ impl<C: Component + Reflect + FromWorld> FromType<C> for ReflectComponent {
8388
let mut component = world.get_mut::<C>(entity).unwrap();
8489
component.apply(reflected_component);
8590
},
91+
remove_component: |world, entity| {
92+
world.entity_mut(entity).remove::<C>();
93+
},
8694
copy_component: |source_world, destination_world, source_entity, destination_entity| {
8795
let source_component = source_world.get::<C>(source_entity).unwrap();
8896
let mut destination_component = C::from_world(destination_world);

0 commit comments

Comments
 (0)