Skip to content

Commit

Permalink
Fix panics and docs when using World schedules (#8364)
Browse files Browse the repository at this point in the history
# Objective

The method `World::try_run_schedule` currently panics if the `Schedules`
resource does not exist, but it should just return an `Err`. Similarly,
`World::add_schedule` panics unnecessarily if the resource does not
exist.

Also, the documentation for `World::add_schedule` is completely wrong.

## Solution

When the `Schedules` resource does not exist, we now treat it the same
as if it did exist but was empty. When calling `add_schedule`, we
initialize it if it does not exist.
  • Loading branch information
JoJoJet authored Apr 12, 2023
1 parent 14abff9 commit f3c7cce
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1708,11 +1708,13 @@ impl World {

// Schedule-related methods
impl World {
/// Runs the [`Schedule`] associated with the `label` a single time.
/// Adds the specified [`Schedule`] to the world. The schedule can later be run
/// by calling [`.run_schedule(label)`](Self::run_schedule) or by directly
/// accessing the [`Schedules`] resource.
///
/// The [`Schedule`] is fetched from the
/// The `Schedules` resource will be initialized if it does not already exist.
pub fn add_schedule(&mut self, schedule: Schedule, label: impl ScheduleLabel) {
let mut schedules = self.resource_mut::<Schedules>();
let mut schedules = self.get_resource_or_insert_with(Schedules::default);
schedules.insert(label, schedule);
}

Expand Down Expand Up @@ -1743,7 +1745,9 @@ impl World {
&mut self,
label: &dyn ScheduleLabel,
) -> Result<(), TryRunScheduleError> {
let Some((extracted_label, mut schedule)) = self.resource_mut::<Schedules>().remove_entry(label) else {
let Some((extracted_label, mut schedule))
= self.get_resource_mut::<Schedules>().and_then(|mut s| s.remove_entry(label))
else {
return Err(TryRunScheduleError(label.dyn_clone()));
};

Expand Down

0 comments on commit f3c7cce

Please sign in to comment.