Skip to content

Panic: "component already borrowed" when using Mut with for-each systems #294

@zerovolts

Description

@zerovolts

Bevy panics when spawning entities inside a system with a component that is used in multiple other for-each systems, where at least one of the systems takes a Mut version of the component.

The problem statement is very specific, but doing any of these fixes the issue:

  • Changing either or both of the systems that take Velocity into Query systems.
  • Removing either of the systems that use Velocity.
  • Changing acceleration_system to take a non-Mut reference.
  • Spawning the projectile entities in a startup system instead.
  • Spawning a single projectile entity in setup alongside the emitter? 🤷‍♂️

Minimal Repro

use bevy::prelude::*;

fn main() {
    App::build()
        .add_default_plugins()
        .add_startup_system(setup.system())
        .add_system(velocity_system.system())
        .add_system(acceleration_system.system())
        .add_system(emitter_system.system())
        .run();
}

struct Emitter;
struct Velocity;
struct Acceleration;

fn setup(mut commands: Commands) {
    commands.spawn((Emitter,));
}

fn velocity_system(velocity: &Velocity) { }

fn acceleration_system(mut velocity: Mut<Velocity>) { }

fn emitter_system(mut commands: Commands, emitter: &Emitter) {
    commands.spawn((Velocity, Acceleration));
}

Error

thread '<unnamed>' panicked at 'bevy_borrow_test::Velocity already borrowed', C:\Users\zach\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\src\libcore\macros\mod.rs:16:9

Minimal repro project containing full error: https://github.com/zerovolts/bevy-borrow-panic

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsP-CrashA sudden unexpected crash

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions