### Example of `EventChannel::extend()` Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/06-errors-and-types.md Shows how to add a vector of events to the channel at once. ```rust channel.extend(vec![event1, event2, event3]); ``` -------------------------------- ### AsyncPlugin Setup Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Configure the AsyncPlugin with default settings or custom schedules and reactors. ```rust // Basic setup app.add_plugins(AsyncPlugin::default_settings()); ``` ```rust // With additional reactors app.add_plugins(AsyncPlugin::default_settings()) .react_to_state::() .react_to_component_change::() .react_to_message::(); ``` ```rust // Custom schedules app.add_plugins( AsyncPlugin::empty() .run_in(Update) .run_in_set(PostUpdate, MySystemSet) ); ``` -------------------------------- ### Handle ResourceNotFound Error Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Shows two ways to handle the ResourceNotFound error: initializing a resource in a setup system and getting a resource with a default value in async code. This is relevant when a resource might not be present. ```rust // In setup system: app.init_resource::(); // Or in async code: let config = AsyncWorld.resource::() .get(|c| c.clone()) .unwrap_or_default(); ``` -------------------------------- ### Plugin Setup and Configuration Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Demonstrates default plugin settings and custom schedule configurations. ```Rust use bevy_defer::AsyncPlugin; // Default settings app.add_plugin(AsyncPlugin::default_settings()); // Custom schedules app.add_plugin(AsyncPlugin::empty().with_busy_schedule()); app.add_plugin(AsyncPlugin::empty().with_schedules(my_schedules)); ``` -------------------------------- ### Example of `EventChannel::take()` Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/06-errors-and-types.md Demonstrates how to safely retrieve an event from the channel using `take()`. ```rust if let Some(event) = channel.take() { // Process event } ``` -------------------------------- ### Example of `EventChannel::push()` Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/06-errors-and-types.md Shows how to add a custom event type to the channel. ```rust channel.push(MyEvent(42)); ``` -------------------------------- ### AsyncWorld Yield Now Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/07-cancellation-and-control-flow.md Example demonstrating yielding execution at the end of the current frame, suitable for continuous loops. ```rust loop { // Do work AsyncWorld.yield_now().await?; } ``` -------------------------------- ### Loading and Waiting for Assets Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/04-fetch-macro.md Shows how to load an asset using fetch! and asynchronously wait for it to be loaded. ```rust commands.spawn_task(|| async { let texture = fetch!(#AsyncWorld.load_asset::("player.png")); let loaded = fetch!(#texture).loaded().await; if loaded { // Use texture } Ok(()) }); ``` -------------------------------- ### Basic AsyncPlugin Setup Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/08-executor-and-systems.md Configure the AsyncPlugin with default settings for basic asynchronous functionality in your Bevy application. ```rust fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins(AsyncPlugin::default_settings()) .run(); } ``` -------------------------------- ### AsyncWorld Sleep Examples Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/07-cancellation-and-control-flow.md Examples demonstrating how to pause asynchronous execution for a duration using seconds or a Duration object. ```rust AsyncWorld.sleep(1.5).await?; // 1.5 seconds AsyncWorld.sleep(Duration::from_secs(2)).await?; ``` -------------------------------- ### Example of `BoxedFuture` Creation Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/06-errors-and-types.md Shows how to create and return a `BoxedFuture` which is a dynamically sized future. ```rust fn create_future() -> BoxedFuture { Box::pin(async { Ok(()) }) } ``` -------------------------------- ### Setup Bevy Defer Plugin Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Add the AsyncPlugin to your Bevy application and configure state and event reactors. ```rust app.add_plugins(AsyncPlugin::default_settings()) .react_to_state::() .register_oneshot_event::(); ``` -------------------------------- ### Example Async Function Returning AccessResult Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/types.md Demonstrates how to define an async function that returns an `AccessResult` for fetching player health. Also shows an example for healing, which returns the default `AccessResult` (void). ```rust async fn get_player_health() -> AccessResult { fetch!(player_entity, Health).get(|h| h.value) } async fn heal_player() -> AccessResult { // Default T = () fetch!(player_entity, Health).get_mut(|h| h.value = 100) } ``` -------------------------------- ### Example of `BoxedSharedFuture` Creation Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/06-errors-and-types.md Illustrates the creation of a `BoxedSharedFuture`, which can be safely shared across threads. ```rust fn create_shared_future() -> BoxedSharedFuture { Box::pin(async { Ok(()) }) } ``` -------------------------------- ### AsyncWorld Sleep Frames Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/07-cancellation-and-control-flow.md Example demonstrating how to pause asynchronous execution for a specific number of frames. ```rust AsyncWorld.sleep_frames(5).await?; // 5 frames ``` -------------------------------- ### Cancellation in Interpolation Setup Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/07-cancellation-and-control-flow.md Sets up two `CancelPrevious` handles for managing sequential animations, where starting a new animation automatically cancels the previous one. ```rust let cancel = CancelPrevious::new(); let cancel2 = cancel.clone(); // Start first animation commands.spawn_task(move || async move { // Animation using TaskCancellation::from(&cancel) Ok(()) }); // Start second animation - automatically cancels first let cancel3 = cancel2.clone(); commands.spawn_task(move || async move { // New animation starts, previous one is cancelled Ok(()) }); ``` -------------------------------- ### Examples of `AccessResult` Usage Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/06-errors-and-types.md Demonstrates how to use `AccessResult` for functions returning either a success value or an `AccessError`. ```rust async fn do_something() -> AccessResult { // Returns Result<(), AccessError> Ok(()) } async fn do_something_else() -> AccessResult { // Returns Result Ok(42) } ``` -------------------------------- ### Async to Sync State Change Example Source: https://github.com/mintlu8/bevy_defer/blob/main/README.md Shows how to change the game state from an asynchronous context to a synchronous one using `AsyncWorld.set_state`. ```rust AsyncWorld.set_state(GameState::Loading); ``` -------------------------------- ### Accessing Multiple Entity Types Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/04-fetch-macro.md Demonstrates fetching multiple entity types and iterating over queries within a spawn_task. ```rust commands.spawn_task(|| async { let player = fetch!(#player_entity); let health = fetch!(player, Health).get(|h| h.value)?; let enemies = fetch!((&Transform, &Enemy)); enemies.for_each(|(t, enemy)| { println!("Enemy at: {}", t.translation); }); Ok(()) }); ``` -------------------------------- ### Turn-based Gameplay Example Source: https://github.com/mintlu8/bevy_defer/blob/main/README.md Demonstrates sequencing actions in a turn-based game using await. This pattern is useful for managing player input and game flow. ```rust move_to(position).await; let damage = attack(enemy).await; show_damage(damage).await; ``` -------------------------------- ### Example Usage of Component Change Signal Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/05-signals-and-reactors.md Demonstrates how to set up `react_to_component_change` for a `ButtonState` component and access the resulting change signal in async code. ```rust #[derive(Component, Clone, Copy, PartialEq, Eq)] enum ButtonState { Normal, Hovered, Pressed } app.react_to_component_change::(); // In async code let change_signal = reactors.get_typed::>(); ``` -------------------------------- ### Complex Queries with Filters Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/04-fetch-macro.md Illustrates performing complex queries with filters, such as fetching entities without a specific component. ```rust commands.spawn_task(|| async { let visible_enemies = fetch!((&Transform, &Enemy), Without); visible_enemies.for_each(|(t, e)| { // Process visible enemies }); Ok(()) }); ``` -------------------------------- ### AsyncResource Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Provides asynchronous access to a resource in the Bevy world. Supports getting, getting mutable access, checking existence, inserting, and removing resources. ```APIDOC ## AsyncResource ### Description Async accessor for a resource. Allows immutable and mutable access, existence checks, insertion, and removal of resources. ### Access Operations - `.get(closure)` - Get immutable access - `.get_mut(closure)` - Get mutable access - `.exists()` - Check existence - `.insert(value)` - Insert or replace - `.remove()` - Remove resource ### Example Usage ```rust let config = AsyncWorld.resource::().get(|cfg| cfg.difficulty)?; AsyncWorld.resource::().get_mut(|cfg| cfg.difficulty = Hard)?; ``` ``` -------------------------------- ### Spawn Simple Asynchronous Task Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Example of spawning a simple asynchronous task that sleeps and prints a message. ```rust commands.spawn_task(|| async { AsyncWorld.sleep(2.0).await?; println!("Done!"); Ok(()) }); ``` -------------------------------- ### Add Asset Dynamically Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Demonstrates how to add a new asset to the world asynchronously and get a handle to it. ```rust let mesh = Mesh::new(PrimitiveTopology::TriangleList); let handle = AsyncWorld.add_asset(mesh)?; ``` -------------------------------- ### Add AsyncPlugin to Bevy App Source: https://github.com/mintlu8/bevy_defer/blob/main/README.md Adds the default settings for the AsyncPlugin to your Bevy application. This is the initial setup required to use bevy_defer. ```rust app.add_plugins(AsyncPlugin::default_settings()) ``` -------------------------------- ### Sync to Async Communication Example Source: https://github.com/mintlu8/bevy_defer/blob/main/README.md Demonstrates sending an event from an async context to a sync system in Bevy. The async code uses fetch to modify an entity's state and then sends a custom event. ```rust async { fetch!(entity, IsJumping).set(|j| *j == true); AsyncWold.send_event(Jump(entity)) } pub fn jump_system(query: Query>) { for name in &query { println!("{} is jumping!", name); } } ``` -------------------------------- ### Event Stream Loop Task Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Example of spawning a task that continuously listens for and handles specific events. ```rust app.register_oneshot_event::(); commands.spawn_task(|| async { loop { match AsyncWorld.get_next_event::().await { Ok(action) => { // Handle action } Err(_) => break, } } }); ``` -------------------------------- ### Example of Drop-Triggered Cancellation Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/07-cancellation-and-control-flow.md Demonstrates how a task is automatically cancelled when the CancelOnDrop handle goes out of scope. ```rust { let _cancel = Cancellation::new().cancel_on_drop(); // Task runs here // Task is cancelled when _cancel goes out of scope } ``` -------------------------------- ### AccessError::NoEntityFound Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Indicates that `query_single()` was used, but no entities matched the query. Use a regular `query()` if multiple entities are expected, or ensure required entities are spawned. ```rust AccessError::NoEntityFound { query: &'static str } ``` ```rust match AsyncWorld.query_single::<&CameraComponent>() .get(|cam| cam.position) { Ok(pos) => println!("Camera at: {}", pos), Err(AccessError::NoEntityFound { .. }) => { println!("No camera found in world"); }, Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Get Asset ID Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/09-assets-and-tweening.md Retrieves the underlying asset ID from an AsyncAsset. No setup is required. ```rust pub fn id(&self) -> AssetId ``` ```rust let id = async_asset.id(); ``` -------------------------------- ### Define BeforeAsyncExecutor Schedule Label Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Defines the BeforeAsyncExecutor schedule label, which runs before `run_async_executor`. By default, this runs watch queries and reactors. Add systems here to run setup logic before tasks are executed. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ScheduleLabel)] pub struct BeforeAsyncExecutor; ``` ```rust app.add_systems(BeforeAsyncExecutor, my_setup_system); ``` -------------------------------- ### Try Convert to Strong Handle Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/09-assets-and-tweening.md Attempts to convert an AsyncAsset into a strong Handle. Returns `Some(Handle)` if successful, or `None` if the asset is a weak reference. No setup is required. ```rust pub fn try_into_handle(self) -> Option> ``` ```rust if let Some(handle) = async_asset.try_into_handle() { // Use handle with sync code } ``` -------------------------------- ### AsyncNonSend Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Provides asynchronous access to `!Send` resources. Similar to `AsyncResource`, it supports getting, getting mutable access, checking existence, inserting, and removing. ```APIDOC ## AsyncNonSend ### Description Async accessor for `!Send` resources. Offers immutable and mutable access, existence checks, insertion, and removal. ### Access Operations - `.get(closure)` - Get immutable access - `.get_mut(closure)` - Get mutable access - `.exists()` - Check existence - `.insert(value)` - Insert or replace - `.remove()` - Remove resource ### Example Usage ```rust let non_send = AsyncWorld.non_send_resource::().get(|data| data.process())?; ``` ``` -------------------------------- ### Set up and Listen to Game Events in Async Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/10-event-channels-and-synchronization.md Demonstrates registering a one-shot event and then listening to it asynchronously. This pattern is useful for signaling state changes or discrete occurrences from sync to async code. ```rust #[derive(Clone)] struct GameEvent(i32); fn setup(app: &mut App) { app.register_oneshot_event::(); } fn send_events(mut channel: ResMut>) { channel.push(GameEvent(1)); channel.push(GameEvent(2)); } fn listen_events(mut commands: Commands) { commands.spawn_task(|| async { loop { match AsyncWorld.get_next_event::().await { Ok(event) => println!("Event: {}", event.0), Err(_) => break, } } }); } ``` -------------------------------- ### AsyncComponent Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Provides asynchronous access to a component on a specific entity. It allows for operations like getting, getting mutable access, checking existence, inserting, and removing components. ```APIDOC ## AsyncComponent ### Description Async accessor for a component on a specific entity. Allows immutable and mutable access, existence checks, insertion, and removal. ### Methods #### `entity()` - **Description**: Get the entity this component belongs to. - **Returns**: `AsyncEntityMut` - The entity mutator. - **Example**: `let entity = component_accessor.entity();` #### `id()` - **Description**: Get the entity ID directly. - **Returns**: `Entity` - The entity ID. - **Example**: `let entity_id = component_accessor.id();` ### Access Operations - `.get(closure)` - Get immutable access - `.get_mut(closure)` - Get mutable access - `.exists()` - Check existence - `.insert(value)` - Insert or replace - `.remove()` - Remove from entity ### Example Usage ```rust let health = entity.component::().get(|h| h.value)?; entity.component::().get_mut(|h| h.value = 100)?; ``` ``` -------------------------------- ### Create AsyncPlugin with Default Settings Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Construct an AsyncPlugin that runs once per frame in the `Update` schedule. This is typically the recommended configuration for most games. ```rust pub fn default_settings() -> Self ``` ```rust app.add_plugins(AsyncPlugin::default_settings()); ``` -------------------------------- ### Getting Entity from AsyncEntityQuery Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Retrieves the entity mutator associated with an AsyncEntityQuery. ```rust let entity = entity_query.entity(); ``` -------------------------------- ### AsyncPlugin::default_settings Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Creates an `AsyncPlugin` that runs once per frame in the `Update` schedule. This is typically the recommended configuration for most games. ```APIDOC ## AsyncPlugin::default_settings ### Description Create an AsyncPlugin that runs once per frame in the `Update` schedule. ### Method ```rust pub fn default_settings() -> Self ``` ### Parameters No parameters. ### Returns `AsyncPlugin` - A plugin configured to run during `Update`. ### Example ```rust app.add_plugins(AsyncPlugin::default_settings()); ``` ``` -------------------------------- ### Get Entity from AsyncComponent Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Retrieves the entity mutator associated with an AsyncComponent. ```rust pub fn entity(&self) -> AsyncEntityMut ``` -------------------------------- ### Getting Asset ID from AsyncAsset Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Retrieves the underlying AssetId from an AsyncAsset reference. ```rust let id = async_asset.id(); ``` -------------------------------- ### Task Spawning and Management Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Illustrates spawning tasks from different Bevy contexts and managing their lifecycle. ```Rust use bevy_defer::{AsyncWorld, AsyncCommands}; // Spawning from World world.spawn_task(async move { /* ... */ }); // Spawning from Commands commands.spawn_task(async move { /* ... */ }); // Spawning from App app.add_system(my_system.pipe(spawn_task)); ``` -------------------------------- ### Getting Entity ID from AsyncEntityQuery Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Retrieves the unique Entity ID for the AsyncEntityQuery. ```rust let entity_id = entity_query.id(); ``` -------------------------------- ### Get Entity ID from AsyncComponent Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Directly retrieves the entity ID from an AsyncComponent. ```rust pub fn id(&self) -> Entity ``` -------------------------------- ### Get AsyncWorld from AsyncEntityMut Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Retrieves the AsyncWorld accessor associated with an AsyncEntityMut instance. ```rust let world = entity_mut.world(); ``` -------------------------------- ### Async Asset Loading Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Demonstrates asynchronous asset loading, batch loading, and state checking. ```Rust use bevy_defer::{AsyncWorld, AssetSet}; // Async asset loading let asset: AsyncAsset = world.get_asset(asset_id).await; // Batch loading let asset_set = AssetSet::new(vec![asset_id1, asset_id2]); world.load_asset_set(asset_set).await; // Asset waiting and state checking if asset.is_loaded() { // ... use asset } else { asset.wait_until_loaded().await; } ``` -------------------------------- ### Fetch Macro for Cleaner Syntax Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Demonstrates the `fetch!` macro for simplifying asynchronous data access. ```Rust use bevy_defer::fetch; async fn example(world: &AsyncWorld) { let (mut component, resource, query) = fetch!( world, AsyncComponent(entity_id), AsyncResource, AsyncQuery ); // ... use fetched data ``` -------------------------------- ### Get AsyncEntityQuery on Entity Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Retrieves an AsyncEntityQuery accessor for a given query data type on an entity. ```rust let transform = entity_mut.query::<&Transform>() .get(|t| t.translation)?; ``` -------------------------------- ### Signals and Reactors for Reactive Programming Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Shows how to use Signals, StateSignal, and Change for reactive patterns. ```Rust use bevy_defer::{Signals, StateSignal, Change}; // Entity with signals entity.insert(Signals::default()); // State signal let state_signal: StateSignal = world.get_state_signal().await; // Component change detection let change: Change = world.get_change(entity_id).await; ``` -------------------------------- ### Get Entity ID from AsyncEntityMut Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Obtains the underlying Bevy Entity ID from an AsyncEntityMut instance. ```rust let entity = entity_mut.id(); ``` -------------------------------- ### AsyncPlugin with System Sets Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/08-executor-and-systems.md Configure AsyncPlugin to run within specific system sets, allowing for fine-grained control over async task execution timing. ```rust #[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone, Copy)] struct AsyncSet; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins( AsyncPlugin::empty() .run_in_set(Update, AsyncSet) ) .run(); } ``` -------------------------------- ### AssetSet::new Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Creates a new AssetSet for managing multiple asset loads. ```APIDOC ## AssetSet::new() ### Description Create a new asset set. ### Method `new` ### Parameters #### Path Parameters - **—** (—) - — - — ### Response #### Success Response - **AssetSet** - A new set. ### Request Example ```rust let set = AssetSet::default().new(); ``` ``` -------------------------------- ### AsyncWorld::now() Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Obtains the elapsed time since the Bevy application's initialization. ```APIDOC ## AsyncWorld::now() ### Description Obtains the total elapsed time since the Bevy application was initialized. ### Method `now(&self) -> Duration` ### Parameters None. ### Returns `Duration` - The elapsed time since application initialization. ### Example ```rust let elapsed = AsyncWorld.now(); println!("Elapsed: {:?}", elapsed); ``` ``` -------------------------------- ### Configure AsyncPlugin to Run in a Schedule and System Set Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Add an executor run in a specific schedule and system set. Returns self for chaining. ```rust pub fn run_in_set(mut self, schedule: impl ScheduleLabel, set: impl SystemSet) -> Self ``` ```rust AsyncPlugin::empty() .run_in_set(Update, MySystemSet) ``` -------------------------------- ### Get Frame Count with AsyncWorld Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Obtain the number of frames that have been executed since the Bevy application was initialized. ```rust let frame = AsyncWorld.frame_count(); ``` -------------------------------- ### Spawning Tasks from Commands Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Spawn tasks using Bevy's commands, including state-scoped tasks that auto-cancel. ```rust commands.spawn_task(|| async { // !Send types can be captured Ok(()) }); ``` ```rust // State-scoped commands.spawn_state_scoped(GameState::Playing, || async { // Auto-cancels when state changes Ok(()) }); ``` -------------------------------- ### Accessing World Data with fetch! Macro Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Use the fetch! macro for convenient access to resources, queries, and components. ```rust // Resource let config = fetch!(GameConfig).get(|c| c.max_level)?; ``` ```rust // Query fetch!((&Transform, &Velocity)).for_each(|(t, v)| { println!("Pos: {}", t.translation); }); ``` ```rust // Component let health = fetch!(entity, Health).get(|h| h.value)?; ``` ```rust // Entity from handle/ID let entity = fetch!(#entity_id); let asset = fetch!(#texture_handle); ``` -------------------------------- ### Accessing Resource Data Asynchronously Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Shows how to get immutable and mutable access to resource data using AsyncResource. ```rust let config = AsyncWorld.resource::() .get(|cfg| cfg.difficulty)?; AsyncWorld.resource::() .get_mut(|cfg| cfg.difficulty = Hard)? ``` -------------------------------- ### AsyncEntityMut Conversions Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Demonstrates conversions for AsyncEntityMut, including from Entity and its Display implementation. ```APIDOC ## AsyncEntityMut Conversions ### From Convert an `Entity` to `AsyncEntityMut`. ### Example ```rust let entity_mut: AsyncEntityMut = my_entity.into(); ``` ### Display Format for debugging. Shows entity name if available, otherwise index and generation. ### Example ```rust println!("{}", entity_mut); // Output: Entity("PlayerCharacter", 2, 0) ``` ``` -------------------------------- ### Get or Create Typed Signal Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/05-signals-and-reactors.md Obtain a typed signal from the Reactors resource. The signal is auto-created if it doesn't exist. ```rust let signal = reactors.get_typed::>(); ``` -------------------------------- ### Bridge Sync to Async with StartLevel Event Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/10-event-channels-and-synchronization.md Implements a sync-to-async bridge by sending a `StartLevel` event from a system to an async task. This pattern is useful for triggering asynchronous operations based on synchronous game state or input. ```rust #[derive(Clone)] struct StartLevel(String); fn level_loader(mut commands: Commands) { commands.spawn_task(|| async { let level_name = AsyncWorld.next_event::().await; println!("Loading level: {}", level_name.0); // Load level asynchronously Ok(()) }); } fn trigger_level( input: Res>, mut channel: ResMut>, ) { if input.just_pressed(KeyCode::Space) { channel.push(StartLevel("level_1".to_string())); } } ``` -------------------------------- ### AsyncEntityQuery Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md An asynchronous accessor for querying components on a specific entity. It provides methods to get the entity itself, its ID, and access its components. ```APIDOC ## AsyncEntityQuery ### Description Asynchronous accessor for querying components on a specific entity. Allows immutable and mutable access to the entity's data. ### Methods #### `entity()` Get the entity this query is for. **Returns:** `AsyncEntityMut` - The entity mutator. **Example:** ```rust let entity = entity_query.entity(); ``` #### `id()` Get the entity ID. **Returns:** `Entity` - The entity ID. **Example:** ```rust let entity_id = entity_query.id(); ``` ### Access Operations - `.get(closure)`: Get immutable access to the entity's matching query data. - `.get_mut(closure)`: Get mutable access to the entity's matching query data. - `.exists()`: Check if the entity matches the query. ### Example ```rust let transform = entity_query.get(|t| t.translation)?; entity_query.get_mut(|mut t| { t.translation.x += 1.0; })?; ``` ``` -------------------------------- ### spawn_task() Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Spawn a task from Commands using a closure. ```APIDOC ## spawn_task()
`fn spawn_task + 'static>( &mut self, f: impl FnOnce() -> F + Send + 'static, ) -> &mut Self` Spawn a task from `Commands` using a closure. ### Parameters #### Path Parameters - **f** (Closure returning future) - Required - Closure that produces the future ### Returns `&mut Self` - Returns self for chaining. ### Note Accepts a closure to allow smuggling `!Send` futures. ### Example ```rust commands.spawn_task(|| async { // Non-Send types can be captured in the closure println!("Task running"); Ok(()) }); ``` ``` -------------------------------- ### Get Filtered AsyncEntityQuery on Entity Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Retrieves a filtered AsyncEntityQuery accessor for a given query data type and filter on an entity. ```rust entity_mut.query_filtered::<&Transform, Without>() .get(|t| /* ... */)?; ``` -------------------------------- ### Register and React to Player Input Events Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/10-event-channels-and-synchronization.md Sets up a system to copy Bevy messages to an event channel for asynchronous consumption. Use this when you need to process game input in a separate async task. ```rust #[derive(Message, Clone)] struct PlayerInput(Vec2); fn setup(app: &mut App) { app.react_to_message::(); } // In system fn send_input(mut sender: EventWriter) { sender.send(PlayerInput(Vec2::new(1.0, 0.0))); } // In async code commands.spawn_task(|| async { loop { let input = AsyncWorld.next_event::().await; println!("Player input: {:?}", input); } }); ``` -------------------------------- ### AccessError::ChannelClosed Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Represents an unexpected closure of an internal async channel. This is a rare internal error, and users should report it if encountered. ```rust AccessError::ChannelClosed ``` -------------------------------- ### AsyncWorld.load_asset_with_settings() Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/09-assets-and-tweening.md Loads an asset with custom settings applied via a closure. This allows for fine-grained control over how an asset is loaded, such as applying specific configurations. ```APIDOC ## AsyncWorld.load_asset_with_settings() ### Description Loads an asset from a path with custom settings. A closure is provided to modify the settings before the asset is loaded, enabling advanced loading configurations. ### Method `load_asset_with_settings` ### Parameters #### Path Parameters - **A** (Generic type) - Required - The type of the asset to load. - **S** (Generic type) - Required - The type of the settings to use for loading. - **path** (`impl Into>`) - Required - The path to the asset. - **f** (Closure) - Required - A closure that takes a mutable reference to the settings and applies configurations. ### Returns `AsyncAsset
` - A strong reference to the asset, which may still be loading. ### Example ```rust let mesh = AsyncWorld.load_asset_with_settings::( "models/player.glb", |settings| { settings.custom_option = true; } )?; ``` ``` -------------------------------- ### AsyncPlugin::busy_schedule Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Creates an `AsyncPlugin` that runs in `PreUpdate`, `Update`, and `PostUpdate`. Use this for games that need higher executor tick frequency or tighter synchronization with system schedules. ```APIDOC ## AsyncPlugin::busy_schedule ### Description Create an AsyncPlugin that runs in `PreUpdate`, `Update`, and `PostUpdate`. ### Method ```rust pub fn busy_schedule() -> Self ``` ### Parameters No parameters. ### Returns `AsyncPlugin` - A plugin configured for busy scheduling. ### Use Case For games that need higher executor tick frequency or tighter synchronization with system schedules. ### Example ```rust app.add_plugins(AsyncPlugin::busy_schedule()); ``` ``` -------------------------------- ### Get AsyncComponent on Entity Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Retrieves an AsyncComponent accessor for a specific component type on an entity. Note: This does not validate component or entity existence. ```rust let health = entity_mut.component::() .get(|h| h.value)?; ``` -------------------------------- ### run_before_async_executor System Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/08-executor-and-systems.md A Bevy system that executes the BeforeAsyncExecutor schedule, typically used for running watch queries and reactors before the main async executor. It should be ordered before run_async_executor. ```rust pub fn run_before_async_executor(world: &mut World) ``` ```rust app.add_systems(Update, run_before_async_executor .before(run_async_executor)); ``` -------------------------------- ### Get AsyncEntityMut for an Entity Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Obtains an AsyncEntityMut for a specific entity ID. Note that this method does not validate if the entity actually exists in the world. ```rust let entity_mut = AsyncWorld.entity(my_entity); ``` -------------------------------- ### Load Asset Asynchronously Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/09-assets-and-tweening.md Loads an asset from a path without waiting for completion. Use this when you need to start loading an asset in the background. ```rust pub fn load_asset( &self, path: impl Into> + Send + 'static, ) -> AsyncAsset ``` ```rust let texture = AsyncWorld.load_asset::("textures/player.png"); // Asset is loading but not yet available ``` -------------------------------- ### Task Cancellation and Control Flow Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/README.md Demonstrates state-scoped task cancellation, cancellation tokens, and control flow primitives. ```Rust use bevy_defer::{AsyncWorld, CancelToken, Yield, Sleep}; // State-scoped cancellation world.cancel_tasks_in_state(MyState::Loading); // Cancellation token let token = CancelToken::new(); let task = world.spawn_task_with_token(token.clone(), async move { /* ... */ }); // Yielding for one frame Yield.await; // Sleeping by time or frames Sleep::new(Duration::from_secs(1)).await; Sleep::frames(5).await; ``` -------------------------------- ### Clear All Events from EventChannel Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/10-event-channels-and-synchronization.md Removes all pending events from the channel. This is typically used to clear events from the previous frame, for example, by the `react_to_message()` function. ```rust channel.clear(); ``` -------------------------------- ### Spawning Tasks from World or App Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Spawn asynchronous tasks directly from the Bevy world or app instance. ```rust world.spawn_task(async { // Task code Ok(()) }); ``` ```rust app.spawn_task(async { // Task code Ok(()) }); ``` -------------------------------- ### State Machine Task Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Shows how to create a task that reacts to state changes in a Bevy state machine. ```rust #[derive(States, Default, Debug, Clone, PartialEq, Eq, Hash)] enum GameState { #[default] Menu, Playing, Paused } app.react_to_state::(); commands.spawn_task(|| async { loop { let signal = AsyncWorld.resource::() .get_typed::>(); match signal.read() { GameState::Playing => { // Game logic } GameState::Paused => { // Paused logic } _ => {} } AsyncWorld.yield_now().await?; } }); ``` -------------------------------- ### Fetch Macro vs. AsyncWorld for Resources Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/04-fetch-macro.md Compares fetching a resource using the fetch! macro and explicit AsyncWorld calls. Ensure the resource type (GameConfig) is accessible. ```rust let config = fetch!(GameConfig).get(|c| c.level)?; ``` ```rust let config = AsyncWorld.resource::().get(|c| c.level?); ``` -------------------------------- ### Accessing Component Data Asynchronously Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Demonstrates getting immutable and mutable access to component data using AsyncComponent's Deref implementations. ```rust let health = entity.component::() .get(|h| h.value)?; entity.component::() .get_mut(|h| h.value = 100)? ``` -------------------------------- ### Create Empty AsyncPlugin Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Construct an AsyncPlugin with no executor runs configured. Use `run_in()` and `run_in_set()` to add runs after construction. ```rust pub fn empty() -> Self ``` ```rust let plugin = AsyncPlugin::empty() .run_in(Update); app.add_plugins(plugin); ``` -------------------------------- ### AccessError::EntityNotFound Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Indicates that an attempt was made to access a non-existent entity. Check if the entity is still alive before accessing it, or use `if entity_is_alive()` checks. ```rust AccessError::EntityNotFound(Entity) ``` ```rust match fetch!(entity, Health).get(|h| h.value) { Ok(health) => println!("Health: {}", health), Err(AccessError::EntityNotFound(e)) => println!("Entity {} doesn't exist", e), Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Send Signal in Bevy System Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/05-signals-and-reactors.md Shows how to send data through a `SignalSender` within a Bevy system. ```rust fn my_system( query: Query>, ) { for sender in query.iter() { sender.send(data); // Send through signal } } ``` -------------------------------- ### Get Elapsed Time Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Retrieves the total elapsed time since the Bevy application was initialized. This is useful for time-based logic within asynchronous operations. ```rust let elapsed = AsyncWorld.now(); println!("Elapsed: {:?}", elapsed); ``` -------------------------------- ### Clone Weak Asset Reference Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/09-assets-and-tweening.md Creates a weak clone of an AsyncAsset, avoiding strong references to keep assets in memory only when needed. No setup is required. ```rust pub fn clone_weak(&self) -> Self ``` ```rust let weak = async_asset.clone_weak(); ``` -------------------------------- ### Register and Use Event Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Demonstrates how to register an event using `register_oneshot_event` and then safely use it in asynchronous code with `AsyncWorld.next_event`. This prevents the EventNotRegistered error. ```rust #[derive(Clone)] struct MyEvent; app.register_oneshot_event::(); // Now safe to use in async let event = AsyncWorld.next_event::().await; ``` -------------------------------- ### State Machine with UI State Signals Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/05-signals-and-reactors.md Sets up Bevy to react to changes in a `UIState` enum and spawns an async task to monitor these state transitions and print messages. ```rust #[derive(Component, Clone, Copy, PartialEq, Eq)] enum UIState { Idle, Hovering, Pressed } #[derive(Default)] struct AppState { // ... } fn setup(app: &mut App) { app.add_plugins(AsyncPlugin::default_settings()) .react_to_component_change::(); // Spawn task to monitor state changes app.spawn_task(|| async { let change_signal = AsyncWorld .resource::() .get_typed::>(); loop { let change = change_signal.read(); match change.to { UIState::Pressed => { println!("Button pressed!"); }, _ => {} } AsyncWorld.yield_now().await; } }); } ``` -------------------------------- ### Reactors Struct Definition Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/types.md Represents the global typed signal management system. It provides a method to get or create typed signals, and is automatically initialized by CoreAsyncPlugin. ```rust pub struct Reactors(Arc); ``` -------------------------------- ### Accessing Single Query Results Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Demonstrates how to get immutable or mutable access to a single query result. Returns an AccessError if zero or multiple entities match. ```rust let camera_transform = AsyncWorld.query_single::<&Transform>() .get(|t| t.translation)?; AsyncWorld.query_single::<&mut Health>() .get_mut(|h| h.value = 100)? ``` -------------------------------- ### apply_commands Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Applies a command queue to the world, executing all queued commands. ```APIDOC ## apply_commands() ### Description Applies a command queue to the world. ### Method `apply_commands` ### Parameters #### Path Parameters - **commands** (`&mut CommandQueue`) - Required - Commands to apply ### Request Example ```rust let mut state = OwnedQueryState::new(world); let mut queue = CommandQueue::default(); // ... queue commands ... state.apply_commands(&mut queue); ``` ``` -------------------------------- ### AsyncPlugin with Custom Schedule Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/08-executor-and-systems.md Integrate AsyncPlugin into custom Bevy schedules, specifying which schedules (e.g., Update, PostUpdate) should run async tasks. ```rust fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugins( AsyncPlugin::empty() .run_in(Update) .run_in(PostUpdate) ) .run(); } ``` -------------------------------- ### Apply Commands to World Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Applies a queue of commands to the Bevy world. Ensure a `CommandQueue` is populated before calling this. ```rust pub fn apply_commands(&mut self, commands: &mut CommandQueue) ``` ```rust let mut state = OwnedQueryState::new(world); let mut queue = CommandQueue::default(); // ... queue commands ... state.apply_commands(&mut queue); ``` -------------------------------- ### Configure AsyncPlugin to Run in a Schedule Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Add an executor run in a specific schedule. Returns self for chaining. ```rust pub fn run_in(mut self, schedule: impl ScheduleLabel) -> Self ``` ```rust AsyncPlugin::empty() .run_in(Update) .run_in(PostUpdate) ``` -------------------------------- ### AsyncQuerySingle Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Provides asynchronous access to a single matching entity based on query data and filters. It allows getting immutable or mutable access to the entity's components. ```APIDOC ## AsyncQuerySingle ### Description Provides asynchronous access to a single matching entity. Returns `AccessError` if zero or multiple entities match the query. ### Methods - `.get(closure)`: Get immutable access to the entity's components. - `.get_mut(closure)`: Get mutable access to the entity's components. ### Example ```rust let camera_transform = AsyncWorld.query_single::<&Transform>() .get(|t| t.translation)?; AsyncWorld.query_single::<&mut Health>() .get_mut(|h| h.value = 100)?; ``` ``` -------------------------------- ### Accessing Entity Data with AsyncEntityQuery Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Demonstrates getting immutable or mutable access to data associated with a specific entity. Use `.exists()` to check if the entity matches the query. ```rust let transform = entity_query.get(|t| t.translation)?; entity_query.get_mut(|mut t| { t.translation.x += 1.0; })?; ``` -------------------------------- ### FetchWorld Trait Implementation Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/04-fetch-macro.md Illustrates trait implementations for FetchWorld, mapping resource and query types to their async counterparts. ```rust pub trait FetchWorld { type Out; fn fetch() -> Self::Out; } // Implemented for: // - `T: Resource` → `AsyncResource` // - `T: QueryData` → `AsyncQuery` // - `(T, F): QueryData + QueryFilter` → `AsyncQuery` ``` -------------------------------- ### Create AsyncQuerySingle Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Creates an AsyncQuerySingle accessor for queries expected to return a single entity. Useful for accessing unique entities like cameras. ```rust let camera_transform = AsyncWorld.query_single::<&Transform>() .get(|t| t.translation)?; ``` -------------------------------- ### SignalId Implementation for Custom Signal Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/types.md Example of implementing the SignalId trait for a custom signal type named PlayerDamaged. This associates the signal with i32 data, representing the damage amount. ```rust struct PlayerDamaged; impl SignalId for PlayerDamaged { type Data = i32; // Damage amount } ``` -------------------------------- ### spawn_task Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Spawns a task to be run on the `AsyncExecutor`. This method can be chained and is available on `World` and `App`. Panics if called outside a Bevy context. ```APIDOC ## spawn_task ### Description Spawn a task to be run on the `AsyncExecutor`. ### Method ```rust fn spawn_task(&mut self, f: impl Future + 'static) -> &mut Self ``` ### Parameters #### Path Parameters - **f** (`impl Future + 'static`) - Required - The async future to spawn ### Returns `&mut Self` - Returns self for chaining. ### Panics If called outside a bevy context. ### Example ```rust world.spawn_task(async { AsyncWorld.sleep(1.0).await; println!("Task completed!"); Ok(()) }); ``` ``` -------------------------------- ### AccessError::QueryConditionNotMet Example Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Occurs when an entity exists but does not match the query's filter or component requirements. Verify that the entity has the necessary components and that filter conditions align with its state. ```rust AccessError::QueryConditionNotMet { entity: Entity, query: &'static str } ``` ```rust match fetch!(entity, Health).get(|h| h.value) { Ok(health) => { /* use health */ }, Err(AccessError::QueryConditionNotMet { entity, query }) => { println!("Entity doesn't have Health component"); }, Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Defer Macro for Cleanup Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/11-quick-reference.md Shows how to use the defer macro to ensure a cleanup function is called automatically when a future completes or is dropped. ```rust let _cleanup = defer! { stop_animation(entity)?; }; do_animation(entity).await?; ``` -------------------------------- ### AsyncAsset Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/03-async-accessors.md Asynchronous accessor for assets, supporting both strong and weak references. It provides methods to get the asset ID, clone weak references, convert to a strong handle, and check if the asset is loaded. ```APIDOC ## AsyncAsset ### Description Asynchronous accessor for assets, supporting both strong and weak references. ### Constructors #### `new_weak()` Create a weak asset reference from an `AssetId`. **Parameters:** - `handle` (`impl Into>`): An asset ID or handle. **Returns:** `AsyncAsset` - Weak reference. **Example:** ```rust let asset = AsyncAsset::::new_weak(asset_id); ``` ### Methods #### `id()` Get the underlying `AssetId`. **Returns:** `AssetId` - The asset ID. **Example:** ```rust let id = async_asset.id(); ``` #### `clone_weak()` Clone as a weak reference. **Returns:** `Self` - A weak clone. **Example:** ```rust let weak = async_asset.clone_weak(); ``` #### `try_into_handle()` Convert to a strong handle if possible. **Returns:** `Option>` - Strong handle if this is strong, `None` for weak. **Example:** ```rust if let Some(handle) = async_asset.try_into_handle() { // Use handle } ``` #### `loaded()` Wait for asset to load. **Returns:** `MaybeChannelOut` - A future that resolves to `true` if loaded, `false` if failed. **Example:** ```rust let loaded = async_asset.loaded().await; ``` ``` -------------------------------- ### Create New AssetSet Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/09-assets-and-tweening.md Creates a new AssetSet from an existing one, allowing for batch loading of assets. ```rust pub fn new(&self) -> AssetSet ``` ```rust let set = AssetSet::default().new(); ``` -------------------------------- ### Get Next Event Asynchronously with Error Handling Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/10-event-channels-and-synchronization.md Asynchronously attempts to retrieve the next event, returning an `AccessResult`. This method provides error handling for cases where the event type might not be registered. ```rust commands.spawn_task(|| async { match AsyncWorld.get_next_event::().await { Ok(event) => println!("Event: {:?}", event), Err(e) => println!("Event error: {}", e), } }); ``` -------------------------------- ### register_oneshot_event() Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/01-core-plugin-and-extensions.md Initialize an EventChannel for oneshot event handling. ```APIDOC ## register_oneshot_event()
`fn register_oneshot_event(&mut self) -> &mut Self` Initialize an `EventChannel` for oneshot event handling. ### Parameters #### Path Parameters - **E** (Generic type) - Required - Event type to register ### Returns `&mut Self` - Returns self for chaining. ### Example ```rust #[derive(Clone)] struct MyEvent(i32); app.register_oneshot_event::(); ``` ``` -------------------------------- ### Process Player Damage Events in Async Task Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/10-event-channels-and-synchronization.md Sets up a system to react to `PlayerDamage` messages and then processes these events within an asynchronous task. This example shows how to combine message reactors with async event consumption for complex game logic. ```rust #[derive(Message, Clone)] struct PlayerDamage(i32); fn setup(app: &mut App) { app.react_to_message::(); } fn send_damage(mut sender: EventWriter) { sender.send(PlayerDamage(10)); } fn process_damage(mut commands: Commands) { commands.spawn_task(|| async { loop { if let Ok(damage_event) = AsyncWorld.get_next_event::().await { println!("Player took {} damage", damage_event.0); let health = fetch!(player_entity, Health) .get(|h| h.value)?; let new_health = health.saturating_sub(damage_event.0); fetch!(player_entity, Health) .get_mut(|h| h.value = new_health)?; } } }); } ``` -------------------------------- ### Create AsyncWorld Instance Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/02-async-world-and-entity.md Constructs an AsyncWorld instance with validation. Ensure this is called within a bevy_defer future context, otherwise it will panic. Direct construction without validation is also possible. ```rust let world = AsyncWorld::new(); ``` -------------------------------- ### Spawn an Async Task Source: https://github.com/mintlu8/bevy_defer/blob/main/README.md Spawns a new asynchronous task using the provided commands. The task will execute the given async closure and can interact with the Bevy world. ```rust commands.spawn_task(|| async move { AsyncWorld.sleep(500.0).await; println!("Hello, World!"); Ok(()) }); ``` -------------------------------- ### Unwrap and Expect for Error Handling Source: https://github.com/mintlu8/bevy_defer/blob/main/_autodocs/errors.md Demonstrates using .expect() to unwrap an Option or Result, providing a custom panic message if it's an error, and .unwrap_or() to provide a default value if an error occurs. ```rust let value = fetch!(entity, Component) .get(|c| c.value) .expect("Component must exist"); let value = fetch!(entity, Component) .get(|c| c.value) .unwrap_or(0); ```