#preferences #bevy #api #storage #final #store #reflection

bevy_simple_preferences

Bevy的简单首选项API

1个不稳定版本

新版本 0.1.0 2024年8月14日

#312 in 游戏开发

MIT/Apache

75KB
1.5K SLoC

bevy_simple_preferences

关于

Bevy首选项简单抽象

为Bevy提供简单的首选项API,允许不同的crate通过简单的首选项抽象进行交互,使最终的应用crate完全控制首选项的存储方式和位置。

此crate主要基于Bevy首选项API提案

示例

首先需要定义一个表示首选项的结构体/枚举。

#[derive(Reflect, Default)]
struct ExampleSettings {
    field_u32: u32,
    some_str: String,
    some_option: Option<String>,
}

然后在你的代码中,只需添加PreferencesPlugin并调用RegisterPreferencesExt::register_preferences

App::new()
    .add_plugins(PreferencesPlugin::persisted_with_app_name("YourAppName"))
    .register_preferences::<ExampleSettings>();

如果你正在实现一个库,你不需要添加PreferencesPlugin,因为最终用户需要自己添加。但你可以在不添加插件的情况下依赖于Preferences参数来读取和写入首选项。

如果最终用户没有添加PreferencesPlugin,则结果是不存储首选项。


impl Plugin for MyCratePlugin {
    fn build(&self, app: &mut App) {
        app.register_preferences::<MyCratePreferences>()
            .add_systems(Update, |my_preferences: Preferences<MyCratePreferences>| {
                // Do stuff with your preferences
                assert!(my_preferences.some_field >= 0);
            });
        ;
    }
}

支持的Bevy版本

Bevy bevy_simple_preferences
0.14 0.1

详细信息

PreferencesPlugin负责定义首选项的存储位置,但已为用户选择了合理的默认值,例如存储路径和格式。

存储路径

默认情况下,以下路径用于存储首选项

平台 示例
本地 dirs::preference_dir/{app_name}/preferences.toml /home/alice/.config/MyApp/preferences.toml
Wasm LocalStorage:{app_name}_preferences LocalStorage:MyApp_preferences

最终用户可以通过使用 PreferencesPlugin::with_storage_type 来个性化这些路径,并使用 PreferencesStorageType 中的任何方便的值。

存储格式

默认情况下,使用以下格式

平台 格式 示例
本地 toml [MyPluginPreferences]\n值= 3
Wasm json { "MyPluginPreferences": { "": 3 } }

可以通过实现 crate::storage::fs::FileStorageFormat 来配置不同的格式(仅适用于本地);

有关如何操作的更多信息,请参阅 crate::storage::fs::FileStorageFormat 的文档。

许可证:MIT OR Apache-2.0

依赖项

~18–33MB
~479K SLoC