#How to pass the lifetime of World within a Bevy Command? Is there any other solution to this command

4 messages · Page 1 of 1 (latest)

winged fossil
#
pub trait ClassCommand<Marker = ()>: Send + 'static {
    fn apply(self, entity: Entity, world: &mut World);

    fn with_entity(self, entity: Entity) -> SettingClass<Marker, Self>
    where
        Self: Sized,
    {
        SettingClass {
            id: entity,
            cmd: self,
            marker: PhantomData,
        }
    }
}

pub trait ClassParam {
    fn get_param(entity: Entity, world: &mut World) -> Self;
}

impl <'w, R: Resource> ClassParam for Res<'w, R>{
    fn get_param(entity: Entity, world: &mut World) -> Self {
        //lifetime may not live long enough
        world.get_resource_ref::<R>().unwrap()
    }
}

impl<F, P> ClassCommand<P> for F
where
    F: Send + 'static + FnOnce(P),
    P: ClassParam,
{
    fn apply(self, entity: Entity, world: &mut World) {
        self(P::get_param(entity, world));
    }
}

pub struct SettingClass<Marker, C: ClassCommand<Marker>> {
    cmd: C,
    id: Entity,
    marker: PhantomData<Marker>,
}

impl<M, C: ClassCommand<M>> Command for SettingClass<M, C>
where
    M: 'static + Send,
{
    fn apply(self, world: &mut World) {
        self.cmd.apply(self.id, world);
    }
}
fleet palm
#

in that case you can specify the lifetime like this:

// -----------------vvvv
pub trait ClassParam<'w> {
    // ----------------------------------vvv
    fn get_param(entity: Entity, world: &'w mut World) -> Self;
}

// ------------------------------vvvv
impl <'w, R: Resource> ClassParam<'w> for Res<'w, R>{
    // ----------------------------------vvv
    fn get_param(entity: Entity, world: &'w mut World) -> Self {
        // does it still error?
        world.get_resource_ref::<R>().unwrap()
    }
}
winged fossil
#

@fleet palm
Thank you for your answer. I have found that the functionality I want to implement is not feasible because Command requires Send+'static, and I need the M pass in my ClassCommand<M>to also be Send+'static, so using the lifecycle is not feasible