Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to run a system X duration after a state change #274

Open
ItsDoot opened this issue Mar 15, 2024 · 0 comments
Open

How to run a system X duration after a state change #274

ItsDoot opened this issue Mar 15, 2024 · 0 comments

Comments

@ItsDoot
Copy link

ItsDoot commented Mar 15, 2024

I've seen this come up every now and then as a question in the Discord, so it's probably worth documenting in the cheatbook.

The following is a solution I've posted to discord:

// We'll use a bevy::time::Timer to wait X time.
// Prefer a bevy Timer over a generic Timer for more accurate readings
#[derive(Resource)]
struct MyStateTimer(Timer);

// When we enter a specific state, start the timer.
fn start_timer(timer: ResMut<MyStateTimer>) {
    timer.0 = Timer::new(YOUR_DURATION_HERE, TimerMode::Once);
}

// We initialize the app with a non-running timer
app.add_resource(MyStateTimer(Timer::new(Duration::from_secs(0), TimerMode::Once)));
// Don't forget to register the timer starting system for when the state is entered.
app.add_systems(OnEnter(MyState), start_timer);

// Now here's where we do our delayed logic
fn my_system(timer: ResMut<MyStateTimer>, /* ... */) {
    // We only run logic if the timer has completed, and only when it has *just* completed
    if (timer.just_finished()) {
        // run your logic here
    }
}

// Don't forget to register it!
app.add_systems(my_system.run_if(in_state(MyState)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant