generic_system/
generic_system.rs1use bevy::prelude::*;
13
14#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, States)]
15enum AppState {
16 #[default]
17 MainMenu,
18 InGame,
19}
20
21#[derive(Component)]
22struct TextToPrint(String);
23
24#[derive(Component, Deref, DerefMut)]
25struct PrinterTick(Timer);
26
27#[derive(Component)]
28struct MenuClose;
29
30#[derive(Component)]
31struct LevelUnload;
32
33fn main() {
34 App::new()
35 .add_plugins(DefaultPlugins)
36 .init_state::<AppState>()
37 .add_systems(Startup, setup_system)
38 .add_systems(
39 Update,
40 (
41 print_text_system,
42 transition_to_in_game_system.run_if(in_state(AppState::MainMenu)),
43 ),
44 )
45 .add_systems(OnExit(AppState::MainMenu), cleanup_system::<MenuClose>)
48 .add_systems(OnExit(AppState::InGame), cleanup_system::<LevelUnload>)
49 .run();
50}
51
52fn setup_system(mut commands: Commands) {
53 commands.spawn((
54 PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)),
55 TextToPrint("I will print until you press space.".to_string()),
56 MenuClose,
57 ));
58
59 commands.spawn((
60 PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)),
61 TextToPrint("I will always print".to_string()),
62 LevelUnload,
63 ));
64}
65
66fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
67 for (mut timer, text) in &mut query {
68 if timer.tick(time.delta()).just_finished() {
69 info!("{}", text.0);
70 }
71 }
72}
73
74fn transition_to_in_game_system(
75 mut next_state: ResMut<NextState<AppState>>,
76 keyboard_input: Res<ButtonInput<KeyCode>>,
77) {
78 if keyboard_input.pressed(KeyCode::Space) {
79 next_state.set(AppState::InGame);
80 }
81}
82
83fn cleanup_system<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) {
86 for e in &query {
87 commands.entity(e).despawn();
88 }
89}