Skip to content

Instantly share code, notes, and snippets.

@tomara-x
Last active March 12, 2024 18:00
Show Gist options
  • Save tomara-x/24c4677068254e59941d5389340d7069 to your computer and use it in GitHub Desktop.
Save tomara-x/24c4677068254e59941d5389340d7069 to your computer and use it in GitHub Desktop.
//! produce inexistent children using DynamicScene duplication
use bevy::{prelude::*, ecs::entity::EntityHashMap};
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
struct Cat;
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
struct Kitten;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, (setup, print).chain())
.register_type::<Cat>()
.register_type::<Kitten>()
.run();
}
fn setup(world: &mut World) {
// spawn a kitten and its parent
let kitten = world.spawn(Kitten).id();
world.spawn(Cat).add_child(kitten);
// create a dynamic scene containing the parent (and its children component)
let mut query = world.query_filtered::<Entity, With<Cat>>();
let scene = DynamicSceneBuilder::from_world(&world)
.allow::<Children>()
.allow::<Cat>()
.extract_entities(query.iter(&world))
.build();
let mut entity_map = EntityHashMap::default();
// write the scene, now we have an extra cat without a kitten
// but it has a children component which contains an inexistent id
let _ = scene.write_to_world(world, &mut entity_map);
}
fn print(
cat_query: Query<(Entity, &Children), With<Cat>>,
existent_query: Query<Entity>,
) {
for (id, children) in cat_query.iter() {
info!("cat_id: {:?}, children: {:?}", id, children);
for kitten_id in children {
if existent_query.contains(*kitten_id) {
info!("kitten {:?} exists! mew!", kitten_id);
} else {
info!("kitten {:?} doesn't exists!", kitten_id);
}
}
}
}
2024-03-12T18:02:13.165911Z  INFO hierarchy: cat_id: 2v1, children: Children([1v1])
2024-03-12T18:02:13.165943Z  INFO hierarchy: kitten 1v1 exists! mew!
2024-03-12T18:02:13.165950Z  INFO hierarchy: cat_id: 3v1, children: Children([4v1])
2024-03-12T18:02:13.165956Z  INFO hierarchy: kitten 4v1 doesn't exists!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment