diff --git a/examples/scene/scene.rs b/examples/scene/scene.rs new file mode 100644 index 0000000000..97e22563c6 --- /dev/null +++ b/examples/scene/scene.rs @@ -0,0 +1,130 @@ +use bevy::{prelude::*, type_registry::TypeRegistry}; + +/// This example illustrates loading and saving scenes from files +fn main() { + App::build() + .add_default_plugins() + // Registering components informs Bevy that they exist. This allows them to be used when loading scenes + // This step is only required if you want to load your components from scene files. + // Unregistered components can still be used in your code, but they will be ignored during scene save/load. + // In the future registering components will also make them usable from the Bevy editor. + // The core Bevy plugins already register their components, so you only need this step for custom components. + .register_component::() + .register_component::() + .add_startup_system(save_scene_system.thread_local_system()) + .add_startup_system(load_scene_system.system()) + .add_system(print_system.system()) + .run(); +} + +// Registered components must implement the `Properties` and `FromResources` traits. +// The `Properties` trait enables serialization, deserialization, dynamic property access, and change detection. +// `Properties` enable a bunch of cool behaviors, so its worth checking out the dedicated `properties.rs` example. +// The `FromResources` trait determines how your component is constructed when it loads. For simple use cases you can just +// implement the `Default` trait (which automatically implements FromResources). The simplest registered component just needs +// these two derives: +#[derive(Properties, Default)] +struct ComponentA { + pub x: f32, + pub y: f32, +} + +// Some components have fields that cannot (or should not) be written to scene files. These can be ignored with +// the #[property(ignore)] attribute. This is also generally where the `FromResources` trait comes into play. +// `FromResources` gives you access to your App's current ECS `Resources` when you construct your component. +#[derive(Properties)] +struct ComponentB { + pub value: String, + #[property(ignore)] + pub time_since_startup: std::time::Duration, +} + +impl FromResources for ComponentB { + fn from_resources(resources: &Resources) -> Self { + let time = resources.get::