Skip to content

Instantly share code, notes, and snippets.

@ItsDoot
Created August 25, 2024 01:18
Show Gist options
  • Save ItsDoot/bfca0b1029475bc92ea4cb8457305266 to your computer and use it in GitHub Desktop.
Save ItsDoot/bfca0b1029475bc92ea4cb8457305266 to your computer and use it in GitHub Desktop.
egui retained widget trees
use bevy::prelude::*;
use bevy_egui::{egui, EguiContexts};
use bevy_retained_egui::{
event::{Clicked, Draw, DrawRoot},
widget::{CentralPanel, Label},
RetainedEguiPlugin,
};
fn main() {
let mut app = App::new();
app.add_plugins(DefaultPlugins)
.add_plugins(RetainedEguiPlugin)
.add_systems(Startup, spawn)
.add_systems(Update, draw)
.observe(CounterButton::on_draw)
.observe(CounterButton::on_click);
app.run();
}
pub fn spawn(mut commands: Commands) {
let root = commands
.spawn(CentralPanel::default())
.with_children(|parent| {
parent.spawn(Label::heading(
"This ui was built using a retained egui widget tree!",
));
parent.spawn(CounterButton { count: 0 });
})
.id();
commands.insert_resource(Root(root));
}
#[derive(Resource)]
pub struct Root(pub Entity);
pub fn draw(mut commands: Commands, root: Res<Root>, mut ctxs: EguiContexts) {
let Some(ctx) = ctxs.try_ctx_mut() else {
return;
};
commands.trigger_targets(DrawRoot { ctx: ctx.clone() }, root.0);
}
#[derive(Component)]
pub struct CounterButton {
pub count: i32,
}
impl CounterButton {
pub fn on_draw(
mut trigger: Trigger<Draw>,
mut commands: Commands,
buttons: Query<&CounterButton>,
) {
let Ok(button) = buttons.get(trigger.entity()) else {
return;
};
let resp = trigger
.event_mut()
.ui
.add(egui::Button::new(format!("Count: {}", button.count)));
if resp.clicked() {
commands.trigger_targets(Clicked, trigger.entity());
}
}
pub fn on_click(trigger: Trigger<Clicked>, mut buttons: Query<&mut CounterButton>) {
let Ok(mut button) = buttons.get_mut(trigger.entity()) else {
return;
};
button.count += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment