you can now despawn entities

This commit is contained in:
Schrottkatze 2025-06-26 19:59:31 +02:00
parent 07e6d8b8c6
commit 7e531d42a8
Signed by: schrottkatze
SSH key fingerprint: SHA256:/raZeWZ2RLThYkX/nq26frnmA4Bi3qRM/hijRmDBa10
4 changed files with 70 additions and 9 deletions

View file

@ -1,14 +1,28 @@
use bevy::{asset::AssetPath, prelude::*};
use std::path::PathBuf;
use bevy::{
asset::{AssetPath, io::AssetSourceEvent},
prelude::*,
};
use crate::debug::{ConsoleLog, DebugEvent, DebugMode};
pub fn plugin(app: &mut App) {
app.add_systems(
Update,
handle_load_gltf.run_if(in_state(DebugMode::Enabled)),
(
handle_load_gltf.run_if(in_state(DebugMode::Enabled)),
handle_despawn,
),
);
}
#[derive(Component, Clone)]
struct Id(String);
#[derive(Component)]
struct HasPath(String);
fn handle_load_gltf(
mut c: Commands,
mut dbg_reader: EventReader<DebugEvent>,
@ -16,11 +30,47 @@ fn handle_load_gltf(
asset_server: Res<AssetServer>,
) {
for ev in dbg_reader.read() {
if let DebugEvent::LoadGltf { asset_path } = ev {
if let DebugEvent::LoadGltf { asset_path, id } = ev {
logger.write(&format!("Loading {asset_path}..."));
let scene_handle = asset_server
.load(GltfAssetLabel::Scene(0).from_asset(AssetPath::from(asset_path.clone())));
c.spawn(SceneRoot(scene_handle));
let mut scene = c.spawn((SceneRoot(scene_handle), HasPath(asset_path.clone())));
if let Some(id) = id {
scene.insert(Id(id.clone()));
}
logger.write(
"Should be loaded now. If nothing happened, check if you might've typoed the path.",
);
}
}
}
fn handle_despawn(
mut c: Commands,
mut dbg_reader: EventReader<DebugEvent>,
mut logger: ResMut<ConsoleLog>,
entities: Query<(Entity, &Id)>,
) {
for ev in dbg_reader.read() {
if let DebugEvent::Despawn { id: target_id } = ev {
let mut count = 0;
entities
.iter()
.filter_map(|(entity, Id(id))| (id == target_id).then_some(entity))
.for_each(|entity| {
count += 1;
c.entity(entity).despawn()
});
if count > 0 {
logger.write(&format!("Despawned {count} entities."));
} else {
logger.err(&format!(
"Couldn't find any entities to despawn with id {target_id:?}."
))
}
}
}
}