Skip to content

Instantly share code, notes, and snippets.

@ChristopherBiscardi
Created July 21, 2024 22:14
Show Gist options
  • Save ChristopherBiscardi/c80085b606a6150baf9f735526624cb4 to your computer and use it in GitHub Desktop.
Save ChristopherBiscardi/c80085b606a6150baf9f735526624cb4 to your computer and use it in GitHub Desktop.
InsertIf for Bevy
use bevy::{ecs::system::EntityCommand, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, (startup, log).chain())
.run();
}
fn startup(mut commands: Commands) {
let is_true = true;
commands.spawn_empty().add(
move |mut entity: EntityWorldMut| {
if is_true {
entity.insert(SpriteBundle::default());
}
},
);
commands.spawn_empty().add(InsertIf {
bundle: SpriteBundle::default(),
cond: || true,
});
commands.spawn_empty().add(InsertIf::new(
SpriteBundle::default(),
|| true,
));
}
fn log(mut commands: Commands, query: Query<Entity>) {
for entity in &query {
commands.entity(entity).log_components();
}
}
/// custom version
struct InsertIf<
F: FnMut() -> bool + Send + 'static,
B: Bundle,
> {
cond: F,
bundle: B,
}
impl<B: Bundle, F: FnMut() -> bool + Send + 'static>
EntityCommand for InsertIf<F, B>
{
fn apply(mut self, id: Entity, world: &mut World) {
if (self.cond)() {
world.entity_mut(id).insert(self.bundle);
}
}
}
impl<B: Bundle, F: FnMut() -> bool + Send + 'static>
InsertIf<F, B>
{
fn new(b: B, f: F) -> Self {
Self { cond: f, bundle: b }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment