generic_system/
generic_system.rs

1//! Generic types allow us to reuse logic across many related systems,
2//! allowing us to specialize our function's behavior based on which type (or types) are passed in.
3//!
4//! This is commonly useful for working on related components or resources,
5//! where we want to have unique types for querying purposes but want them all to work the same way.
6//! This is particularly powerful when combined with user-defined traits to add more functionality to these related types.
7//! Remember to insert a specialized copy of the system into the schedule for each type that you want to operate on!
8//!
9//! For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html>
10//! or <https://doc.rust-lang.org/rust-by-example/generics.html>
11
12use 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        // Cleanup systems.
46        // Pass in the types your system should operate on using the ::<T> (turbofish) syntax
47        .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
83// Type arguments on functions come after the function name, but before ordinary arguments.
84// Here, the `Component` trait is a trait bound on T, our generic type
85fn cleanup_system<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) {
86    for e in &query {
87        commands.entity(e).despawn();
88    }
89}