A minimal example showing how to perform asynchronous work in Bevy using [AsyncComputeTaskPool] for parallel task execution and a crossbeam channel to communicate between async tasks and the main ECS thread.
This example demonstrates how to spawn detached async tasks, send completion messages via channels, and dynamically spawn ECS entities (cubes) as results from these tasks. The system processes async task results in the main game loop, all without blocking or polling the main thread.
use ;
use ;
use Delay;
use Rng;
use Duration;
const NUM_CUBES: i32 = 6;
const LIGHT_RADIUS: f32 = 8.0;
/// Spawns async tasks on the compute task pool to simulate delayed cube creation.
///
/// Each task is executed on a separate thread and sends the result (cube position)
/// back through the `CubeChannel` once completed. The tasks are detached to
/// run asynchronously without blocking the main thread.
///
/// In this example, we don't implement task tracking or proper error handling.
/// Handles the completion of async tasks and spawns ECS entities (cubes)
/// based on the received data. The function reads from the `CubeChannel`'s
/// receiver to get the results (cube positions) and spawns cubes accordingly.
/// Sets up a communication channel (`CubeChannel`) to send data between
/// async tasks and the main ECS thread. The sender is used by async tasks
/// to send the result (cube position), while the receiver is used by the
/// main thread to retrieve and process the completed data.
/// A channel for communicating between async tasks and the main thread.
/// Represents the completion of a cube task, containing the cube's transform
/// Resource holding the mesh handle for the box (used for spawning cubes)
;
/// Resource holding the material handle for the box (used for spawning cubes)
;
/// Sets up the shared mesh and material for the cubes.
/// Sets up the environment by spawning the ground, light, and camera.
/// Rotates the point light around the origin (0, 0, 0)