src/bin/lesson06_attach.rs
原文件:Doc/tutorial/src/bin/lesson06_attach.rs。
阅读快照 以下内容来自 2026-11-17 导入时的本地源码,后续不会自动同步。编辑、编译和运行请回到原项目;本页 Markdown 不是可直接编译的源文件。
在原项目根目录运行:
cargo run --manifest-path Doc/tutorial/Cargo.toml --bin lesson06_attach
use bevy::{ecs::system::SystemParam, prelude::*};
use bevy_immediate::{
Imm,
attach::{BevyImmediateAttachPlugin, ImmediateAttach},
ui::{CapsUi, clicked::ImmUiClicked, text::ImmUiText},
};
use bevy_immediate_tutorial::{app, button, camera};
#[derive(Component)]
struct CounterRoot {
value: u32,
}
#[derive(SystemParam)]
struct CounterParams<'w, 's> {
roots: Query<'w, 's, &'static mut CounterRoot>,
}
impl ImmediateAttach<CapsUi> for CounterRoot {
type Params = CounterParams<'static, 'static>;
fn construct(ui: &mut Imm<CapsUi>, params: &mut CounterParams) {
let root_entity = ui.current_entity().expect("attach supplies a root entity");
let mut state = params.roots.get_mut(root_entity).expect("root exists");
let mut add = ui.ch_id("add").on_spawn_insert(button).add(|ui| {
ui.ch_id("caption").text("+1");
});
if add.clicked() {
state.value += 1;
}
ui.ch_id("value")
.text(format!("Local count: {}", state.value));
}
}
fn main() {
app("06 - Two independent counters")
.add_plugins(BevyImmediateAttachPlugin::<CapsUi, CounterRoot>::new())
.add_systems(Startup, (camera, setup))
.run();
}
fn setup(mut commands: Commands) {
for (left, initial) in [(20.0, 0), (340.0, 100)] {
commands.spawn((
CounterRoot { value: initial },
Node {
position_type: PositionType::Absolute,
left: Val::Px(left),
top: Val::Px(30.0),
width: Val::Px(280.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(12.0),
padding: UiRect::all(Val::Px(16.0)),
..default()
},
BackgroundColor(Color::srgb(0.08, 0.09, 0.12)),
));
}
}