Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/app/persisting_preferences.rs
30632 views
1
//! Demonstrates persistence of user preferences.
2
//!
3
//! A counter is shown in the window. It can be incremented and decremented via input press.
4
//! Its value persists between app sessions via user preferences.
5
//!
6
//! On desktop, if you quit the app and then restart it, the counter value should display
7
//! the most recent value the app had before exiting.
8
//! On web, if you navigate away and then come back to the window, the counter
9
//! should display the most recent value the app had before navigating away.
10
use std::time::Duration;
11
12
use bevy::{
13
prelude::*,
14
settings::{
15
PreferencesPlugin, ReflectSettingsGroup, SavePreferencesDeferred, SavePreferencesSync,
16
SettingsGroup,
17
},
18
window::{ExitCondition, WindowCloseRequested},
19
};
20
21
fn main() {
22
App::new()
23
.add_plugins(DefaultPlugins.set(WindowPlugin {
24
// We want to intercept the exit so that we can save prefs.
25
exit_condition: ExitCondition::DontExit,
26
primary_window: Some(Window {
27
title: "Prefs Counter".into(),
28
..default()
29
}),
30
..default()
31
}))
32
.add_plugins(PreferencesPlugin::new(
33
"org.bevy.examples.persisting_preferences",
34
))
35
.add_systems(Startup, setup)
36
.add_systems(Update, (show_count, change_count, on_window_close))
37
.run();
38
}
39
40
#[derive(Resource, SettingsGroup, Reflect, Default)]
41
#[reflect(Resource, SettingsGroup, Default)]
42
struct Counter {
43
count: i32,
44
}
45
46
/// A different settings group which has the name group name as the previous. The two groups will be
47
/// merged into a single section in the config file.
48
#[derive(Resource, SettingsGroup, Reflect, Default)]
49
#[reflect(Resource, SettingsGroup, Default)]
50
#[settings_group(group = "counter")]
51
#[expect(
52
dead_code,
53
reason = "Example showing additional settings in the same group"
54
)]
55
struct OtherSettings {
56
enabled: bool,
57
}
58
59
#[derive(Component)]
60
struct CounterDisplay;
61
62
fn setup(mut commands: Commands) {
63
commands.spawn((Camera::default(), Camera2d));
64
commands
65
.spawn(Node {
66
width: percent(100),
67
height: percent(100),
68
display: Display::Flex,
69
flex_direction: FlexDirection::Column,
70
align_items: AlignItems::Center,
71
justify_content: JustifyContent::Center,
72
..default()
73
})
74
.with_children(|parent| {
75
parent.spawn((
76
Text::new("---"),
77
TextFont {
78
font_size: FontSize::Px(33.0),
79
..default()
80
},
81
CounterDisplay,
82
TextColor(Color::srgb(0.9, 0.9, 0.9)),
83
));
84
parent.spawn((
85
Text::new("Press SPACE to increment, BACKSPACE to decrement."),
86
TextFont {
87
font_size: FontSize::Px(20.0),
88
..default()
89
},
90
));
91
});
92
}
93
94
fn show_count(mut query: Query<&mut Text, With<CounterDisplay>>, counter: Res<Counter>) {
95
if counter.is_changed() {
96
for mut text in query.iter_mut() {
97
text.0 = format!("Count: {}", counter.count);
98
}
99
}
100
}
101
102
fn change_count(
103
mut counter: ResMut<Counter>,
104
keyboard: Res<ButtonInput<KeyCode>>,
105
mut commands: Commands,
106
) {
107
let mut changed = false;
108
if keyboard.just_pressed(KeyCode::Space) {
109
counter.count += 1;
110
changed = true;
111
}
112
if keyboard.just_pressed(KeyCode::Backspace) || keyboard.just_pressed(KeyCode::Delete) {
113
counter.count -= 1;
114
changed = true;
115
}
116
117
if changed {
118
commands.queue(SavePreferencesDeferred(Duration::from_secs_f32(0.1)));
119
}
120
}
121
122
fn on_window_close(mut close: MessageReader<WindowCloseRequested>, mut commands: Commands) {
123
// Save preferences immediately, then quit.
124
if let Some(_close_event) = close.read().next() {
125
commands.queue(SavePreferencesSync::IfChanged);
126
commands.queue(ExitAfterSave);
127
}
128
}
129
130
struct ExitAfterSave;
131
132
impl Command for ExitAfterSave {
133
type Out = ();
134
135
fn apply(self, world: &mut World) {
136
world.write_message(AppExit::Success);
137
}
138
}
139
140