#Making a StateScoped spawn helper

3 messages · Page 1 of 1 (latest)

sharp ledge
#

Hi, I'm still working out good practises for rust and bevy and find that I often forget to apply state scoped to certain entities that can cause issue later. I was wondering about implementing a trait on Commands to make a state_scoped_spawn to make me less likely to forget to insert it. I don't think require will help me out here as this state is large part of my game and I have a lot of completely separate components that need to be de spawned on leaving this state.

I just had a feeling I might be setting myself up for something bad here, so any thoughts would be welcome. Thanks

abstract parrot
#

I've recently started running into the same problem and had exactly the same thoughts. Having to be incredibly vigilant and thoughtful every time I use commands.spawn at risk of memory leaks and unintended behaviour feels like it goes against everything rust usually endorses.

atm a command trait feels like the best alternative but I agree that this issue probably deserves a bit more community attention to come with a better system or best practices

abstract parrot
#

Works quite nicely

use bevy::prelude::*;

pub trait CommandsExt {
    /// Spawns an entity with the [`StateScoped`] component so that it gets despawned when the
    /// given state is exited.
    fn spawn_scoped<T: Bundle, S: States>(&mut self, bundle: T, state: S) -> EntityCommands;
}

impl<'w, 's> CommandsExt for Commands<'w, 's> {
    fn spawn_scoped<T: Bundle, S: States>(&mut self, bundle: T, state: S) -> EntityCommands {
        let mut commands = self.spawn(bundle);
        commands.insert(StateScoped(state));
        commands
    }
}