#Conditionally adding a component to an entity in the spawning process

6 messages · Page 1 of 1 (latest)

misty badge
#

Hey, I made a system to spawn Towers depending on their Type (I have a TowerType enum). It looks like this:

commands.spawn((
            SpriteSheetBundle {
                texture,
                atlas: TextureAtlas {
                    layout: texture_atlas_layout,
                    index: animation_indices.first,
                },
                transform: Transform::from_translation(tower_position).with_scale(tower_scale),
                ..default()
            },
            animation_indices,
            AnimationTimer(Timer::from_seconds(animation_frame_duration, TimerMode::Repeating)),
            Tower {
                tower_type: *tower_type,
                cooldown: tower_type.cooldown(),
            }
));

Now I want to conditionally insert the Component ShouldRotate to it, if tower_type.has_rotation() is true
I tried it by assigning commands.spawn() to a variably let mut tower = commands.spawn($BUNDLE); and then doing

if tower_type.has_rotation() {
            tower.insert(ShouldRotate);
}

This however does not work because of rusts borrowing rules.
Can I archive this without copying the entire commands.spawn()?

sterile lark
#

What exactly is the borrow checker saying? What you're saying should be possible without borrow checker violations.

misty badge
# sterile lark What exactly is the borrow checker saying? What you're saying should be possible...

It says:

error[E0716]: temporary value dropped while borrowed
  --> src/tower.rs:25:25
   |
25 |           let mut tower = commands.spawn((
   |  _________________________^
26 | |             SpriteSheetBundle {
27 | |                 texture,
28 | |                 atlas: TextureAtlas {
...  |
40 | |             }
41 | |         ))
   | |__________^ creates a temporary value which is freed while still in use
...
52 |           });
   |             - temporary value is freed at the end of this statement
53 |           if tower_type.has_rotation() {
54 |               tower.insert(ShouldRotate);
   |               ----- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

solemn aspen
#

writing this off my memory, could have some typos/wrong names.
but something like this should work!