Skip to main content

Crate bevy_settings_lib

Crate bevy_settings_lib 

Source
Expand description

A flexible settings management library for Bevy with async saving, multiple formats, and Configuration/Preferences separation.

This library provides a convenient way to save, load, and reload settings in Bevy applications. It supports text formats (TOML, JSON) and binary (postcard) with atomic write‑then‑rename to prevent file corruption.

§Features

  • Any number of configurations – each configuration has its own data type and file name.
  • File names can be explicit or derived from the struct name (automatically converted to snake_case).
  • Asynchronous saving with atomic write‑then‑rename – files are never left in a corrupted state.
  • Format support: TOML (default), JSON, binary (postcard).
  • Load from OS‑standard directories (via directories crate) or from the game’s local folder.
  • Events: PersistSetting<S>, PersistAllSettings, ReloadSetting<S>, SettingsSaveError<S>.
  • Partial loading – if a file does not exist, S::default() is used.
  • Validation – every settings type must implement ValidatedSetting to normalize values after loading and before saving.

§Quick Example

use bevy::prelude::*;
use bevy_settings_lib::{SettingsPlugin, PersistSetting, SettingsPluginConfig, FormatKind, ValidatedSetting, SettingsStorage};
use serde::{Serialize, Deserialize};

#[derive(Resource, Default, Serialize, Deserialize, Clone, Debug, PartialEq)]
struct MySettings {
    volume: f32,
    fullscreen: bool,
}

// Mandatory validation implementation (can be empty if no validation needed)
impl ValidatedSetting for MySettings {
    fn validate(&mut self) {
        self.volume = self.volume.clamp(0.0, 1.0);
    }
}

fn main() {
    // Use the system configuration directory (AppData, ~/.config, etc.)
    let config = SettingsPluginConfig {
        format: FormatKind::Toml,
        company: "MyCompany".into(),
        project: "MyGame".into(),
        file_name: None, // auto‑name → "my_settings"
        storage: SettingsStorage::SystemConfigDir,
        ..Default::default()
    };
    App::new()
        .add_plugins(SettingsPlugin::<MySettings>::from_config(config))
        .add_systems(Update, save_after_delay)
        .run();
}

fn save_after_delay(
    mut commands: Commands,
    time: Res<Time>,
    mut timer: Local<Option<Timer>>,
) {
    // Create a one‑shot timer on first run
    if timer.is_none() {
        *timer = Some(Timer::from_seconds(2.0, TimerMode::Once));
    }
    let timer = timer.as_mut().unwrap();
    timer.tick(time.delta());
    if timer.just_finished() {
        commands.trigger(PersistSetting::<MySettings> { value: None });
    }
}

§Important Notes

  • Asynchronous saving: When the application exits, the last changes may be lost if the save thread hasn’t finished. For guaranteed persistence, implement synchronous saving (e.g., in an OnExit system).
  • Company and project names must not contain invalid characters for ProjectDirs and cannot be empty when using SystemConfigDir – the library will panic. With GameLocalDir these fields are optional (may be empty).
  • No auto‑save – the developer decides when to trigger saving.

§Plugin Configuration

Use SettingsPluginConfig to choose the format, domain, company, project (for directory), file name, and storage type. Defaults are TOML format, domain "com", and SystemConfigDir storage.

let config = SettingsPluginConfig {
    format: FormatKind::Json,
    company: "MyCompany".into(),
    project: "MyGame".into(),
    file_name: Some("custom_name".into()),
    storage: SettingsStorage::GameLocalDir, // save next to the .exe
    ..Default::default()
};
app.add_plugins(SettingsPlugin::<MySettings>::from_config(config));

Structs§

JsonFormat
PersistAllSettings
PersistSetting
ReloadSetting
SettingsPlugin
SettingsPluginConfig
SettingsSaveError
Event emitted when a settings save operation fails.
TomlFormat

Enums§

FormatKind
SettingsError
SettingsStorage
Storage type for settings files.

Traits§

Setting
SettingsFormat
ValidatedSetting
Trait for validating and normalizing setting values. Mandatory to implement for all types used with SettingsPlugin. Called automatically after loading (including from file), after reloading, after default(), as well as before saving and when setting a new value via the PersistSetting event. If validation is not needed, implement the method as empty.

Type Aliases§

SettingsResult