Skip to content

Restore read-only World::iter_entities or provide infallible equivalent #22657

@chengts95

Description

@chengts95

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

This issue highlights a regression introduced in the transition from Bevy 0.17 to 0.18. The deprecation and subsequent removal of World::iter_entities() has created a gap in functionality for purely read-only access patterns. This was raised by #6228.

Bevy 0.17 has deprecated World::iter_entities() and ask users to use World::Query::<EntityRef>, however World::Query requires mutable world ptr. World::try_query can use read-only world, but from semantics, get active entity ids does not require any try and it is uncertain if World::try_query return Err but the World::iter_entities() should not fail in any situation.

This has unintended side effect on codes relying on World::iter_entities() and no alternative is provided. It is better to readd the API to bevy in the future.

What solution would you like?

Add function similar to following to World so we can query all ids/refs of active entities from read-only context again.

/// Returns an [`Entity`] iterator of current entities.
///
/// This is useful in contexts where you only have read-only access to the [`World`].
#[inline]
pub fn iter_entities(world: &World) -> impl Iterator<Item = Entity> + '_ {
    world
        .archetypes()
        .iter()
        .flat_map(|archetype| archetype.entities().iter().map(|entity| entity.id()))
}

Fix the documentation in Bevy 0.17 since it ignored original motivation of #6228.

What alternative(s) have you considered?

  1. Write examples to tell users how to use archetype APIs and achieve the same functionality.
  2. Have a read_only_query so the query can be performed on &World.

Additional context

The original issue #6228.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ECSEntities, components, systems, and eventsC-FeatureA new feature, making something new possibleD-StraightforwardSimple bug fixes and API improvements, docs, test and examplesS-Ready-For-ImplementationThis issue is ready for an implementation PR. Go for it!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions