bevy/crates/bevy_app
Joseph d66c868e6f
Expressively define plugins using functions (#11080)
# Objective

Plugins are an incredible tool for encapsulating functionality. They are
low-key one of Bevy's best features. Combined with rust's module and
privacy system, it's a match made in heaven.

The one downside is that they can be a little too verbose to define. 90%
of all plugin definitions look something like this:

```rust
pub struct MyPlugin;

impl Plugin for MyPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<CameraAssets>()
           .add_event::<SetCamera>()
           .add_systems(Update, (collect_set_camera_events, drive_camera).chain());
    }
}
```

Every so often it gets a little spicier:

```rust
pub struct MyGenericPlugin<T>(PhantomData<T>);

impl<T> Default for MyGenericPlugin<T> { 
    fn default() -> Self { ... }
 }

impl<T> Plugin for MyGenericPlugin<T> { ... }
```

This is an annoying amount of boilerplate. Ideally, plugins should be
focused and small in scope, which means any app is going to have a *lot*
of them. Writing a plugin should be as easy as possible, and the *only*
part of this process that carries any meaning is the body of `fn build`.

## Solution

Implement `Plugin` for functions that take `&mut App` as a parameter.

The two examples above now look like this:

```rust
pub fn my_plugin(app: &mut App) {
    app.init_resource::<CameraAssets>()
       .add_event::<SetCamera>()
       .add_systems(Update, (collect_set_camera_events, drive_camera).chain());
} 

pub fn my_generic_plugin<T>(app: &mut App) {
    // No need for PhantomData, it just works.
}
```

Almost all plugins can be written this way, which I believe will make
bevy code much more attractive. Less boilerplate and less meaningless
indentation. More plugins with smaller scopes.

---

## Changelog

The `Plugin` trait is now implemented for all functions that take `&mut
App` as their only parameter. This is an abbreviated way of defining
plugins with less boilerplate than manually implementing the trait.

---------

Co-authored-by: Federico Rinaldi <gisquerin@gmail.com>
2024-01-27 02:40:15 +00:00
..
src Expressively define plugins using functions (#11080) 2024-01-27 02:40:15 +00:00
Cargo.toml Standardize toml format with taplo (#10594) 2023-11-21 01:04:14 +00:00
README.md add and fix shields in Readmes (#9993) 2023-10-15 00:52:31 +00:00

Bevy App

License Crates.io Downloads Docs Discord

This crate is about everything concerning the highest-level, application layer of a Bevy app.