bevyengine / bevyengine/bevy

Filtered observers

Open
#15,287 1 comment 9 reactions 0 assignees View on GitHub
A-ECS C-Feature D-Modest X-Uncontroversial
Dominant language
Rust
Stars
48.2k
Forks
4.8k
Avg merge
3d 22h
Merged PRs (30d)
161

Description

## What problem does this solve or what need does it fill?

When working with lifecycle observers (`OnAdd`, `OnRemove`, `OnInsert` and `OnReplace`), simply watching for changes to a single component type is often too broad. Instead, it's common to want to filter for the addition / removal of a component *and* the presence of another component.

## What solution would you like?

Add another generic `F` to `Trigger`, which ensures that entities match that filter before observers are triggered targeting that entity.

## What alternative(s) have you considered?

This can be worked around now by adding a second query to your observer, and checking if the target entity is comtained in the query. This is heavy on boilerplate for such a common pattern, and wastes work by dispatching events and repeatedly regenerating the query.

We could instead add a generic `F: QueryFilter` filter to `OnAdd` and other lifecycle observers , defaulting to `()`. If this generic is set, verify that the target entity matches the provided filter before triggering the observer.

On reflection, I like this solution less than modifying `Trigger`, as it's less general / powerful and requires more duplication. It's also less consistent with the existing `B: Bundle` generic, which is found on `Trigger`, not on e.g. `OnAdd`.

## Additional context

https://github.com/bevyengine/bevy/issues/14649 is related but distinct.

#15325 proposes a change to the first generic.

Discussed [on Discord](https://discordapp.com/channels/691052431525675048/749335865876021248/1286039424609550376) with @maniwani and @NiseVoid.

Contributor guide

Open the contributing guide

Research direction

Start by tracing Trigger and the lifecycle observers OnAdd, OnRemove, OnInsert, and OnReplace, then review related issue #14649 and proposal #15325 for API constraints. Determine how a query filter could be associated with Trigger and how observer dispatch should check the target entity. Done means observers can restrict events to entities matching the filter without the extra query workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
game-dev
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.