bevyengine/bevy · error

Attempted to initialize invalid bits as an entity index

Error message

Attempted to initialize invalid bits as an entity index

What it means

Runtime panic from EntityIndex::from_bits: the u32 argument does not encode a valid NonMax entity index (i.e. it is the sentinel u32::MAX reserved to mark 'no entity'). Bits are only meaningful when produced by to_bits in the same running application; reconstructing any other value hits this debug assertion-style guard.

Source

Thrown at crates/bevy_ecs/src/entity/mod.rs:194

    /// Gets some bits that represent this value.
    /// The bits are opaque and should not be regarded as meaningful.
    #[inline(always)]
    const fn to_bits(self) -> u32 {
        // SAFETY: NonMax is repr transparent.
        unsafe { mem::transmute::<NonMaxU32, u32>(self.0) }
    }

    /// Reconstruct an [`EntityIndex`] previously destructured with [`EntityIndex::to_bits`].
    ///
    /// Only useful when applied to results from `to_bits` in the same instance of an application.
    ///
    /// # Panics
    ///
    /// This method will likely panic if given `u32` values that did not come from [`EntityIndex::to_bits`].
    #[inline]
    const fn from_bits(bits: u32) -> Self {
        Self::try_from_bits(bits).expect("Attempted to initialize invalid bits as an entity index")
    }

    /// Reconstruct an [`EntityIndex`] previously destructured with [`EntityIndex::to_bits`].
    ///
    /// Only useful when applied to results from `to_bits` in the same instance of an application.
    ///
    /// This method is the fallible counterpart to [`EntityIndex::from_bits`].
    #[inline(always)]
    const fn try_from_bits(bits: u32) -> Option<Self> {
        match NonZero::<u32>::new(bits) {
            // SAFETY: NonMax and NonZero are repr transparent.
            Some(underlying) => Some(Self(unsafe {
                mem::transmute::<NonZero<u32>, NonMaxU32>(underlying)
            })),
            None => None,
        }
    }
}

View on GitHub (pinned to 396ca72708)

Solutions

  1. Only feed from_bits values that came from EntityIndex::to_bits in the same process
  2. Persist entities via a proper serialization mapping instead of raw bits
  3. If storing externally, check the value is not u32::MAX before reconstructing
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/bevy_ecs/src/entity/mod.rs:194 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of bevyengine/bevy@396ca72708 (2026-08-20). Data as JSON: /api/errors/d2573b6356d0b77d. Report an issue: GitHub.