makspll / bevy_mod_scripting

Bevy Scripting Plugin
Apache License 2.0
391 stars 30 forks source link

Send Priority event from ScriptWorld #74

Open zwazel opened 11 months ago

zwazel commented 11 months ago

Hi, love this crate!

I just came across a small issue. I need to send out PriorityEvents from a rust function that is registered as a script function. So it has only access to the ScriptWorld.

With the Normal Bevy Events I can just use world.send_event(). But I can't seem to figure out how to send out priority events with only having the ScriptWorld.

Did I miss anything?

makspll commented 11 months ago

Hi @zwazel thanks! What do you mean by a rust function registered as a script function, am I correct in thinking you're trying to send out events back from the script to the bevy world? In this case you can do something similar to world.send_event which is defined using world.send_event_batch like so:

    /// Sends a batch of [`Event`]s from an iterator.
    #[inline]
    pub fn send_event_batch<E: Event>(&mut self, events: impl IntoIterator<Item = E>) {
        match self.get_resource_mut::<Events<E>>() {
            Some(mut events_resource) => events_resource.extend(events),
            None => bevy_utils::tracing::error!(
                    "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ",
                    std::any::type_name::<E>()
                ),
        }
    }

in this case instead of Events you'll simply use PriorityEvents like so:

    /// Sends a batch of [`Event`]s from an iterator.
    #[inline]
    pub fn send_event_batch<E: Event>(&mut self, events: impl IntoIterator<Item = E>, prio: u32) {
        match self.get_resource_mut::<PriorityEvents<E>>() {
            Some(mut events_resource) =>events_resource.events.extend(events.map(|v| EventInstance::new(v, prio))),
            None => bevy_utils::tracing::error!(
                    "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ",
                    std::any::type_name::<E>()
                ),
        }
    }
makspll commented 11 months ago

I should probably extend the world API with a custom trait containing priority event dispatchers tbh