Manual

Manual

Components from Rust and Bevy

C# can read and write components it did not declare: Bevy's own, a Bevy plugin's, and those of your game's Rust crate. This page covers finding such a component by name, the fields the engine describes and those it leaves out, reading and writing them in systems and between frames, enums, putting one on an entity, and finding out what an entity carries. How C# sees a Rust component introduces the idea.

Why C# does not copy their layout

A component declared in C# is laid out as C# says, so a system reads it as a Span<T>. A component with a Rust type is laid out by the Rust compiler, which may put its fields in any order and pad them as it likes. Bevy's Transform is the example: its rotation is stored first and its position 16 bytes in, which nothing in its Rust source suggests, and a later Rust or Bevy could move them again.

So the engine reports where each field really is, from what the compiler did, and C# reads it there, straight in Bevy's memory with nothing copied. Transform and GlobalTransform have C# structs of their own, checked against those reports as the game starts (see Transforms and parents). Everything else is reached through its layout.

Finding a component by name

world.LayoutOf(name) finds a component and describes it:

ComponentLayout light = world.LayoutOf("PointLight");ComponentField range = light["range"];

The name is looked for among the engine's own components first, then those declared in C#, then every component Bevy's type registry knows, by its short name or, where two types share one, by its full Rust path. A component of a Bevy plugin is found when it derives Reflect with #[reflect(Component)], as plugins in Bevy's ecosystem do already; one in your own crate, when it is declared as Rust in a game shows. A name nothing answers to throws an AbyssException; world.ComponentByName(name) asks the same and gives null instead.

ComponentLayout memberWhat it is
ComponentThe name it was found by.
IdIts ComponentId.
SizeHow many bytes one value takes, which is also the distance from one row's value to the next.
FieldsThe fields the engine describes, each a ComponentField.
this[name]A field by its name; throws an ArgumentException for one not described.
Has(name)Whether a field of that name is described.
Read(), Write()Terms for a system's query, as a ComponentType<T> gives.

The fields a layout describes

A ComponentField has the field's Name as Rust spells it, its Offset in bytes, its Kind, its Count of values and its Size. A field is described when it is one of these:

KindRustRead in C# as
F32f32float
F64f64double
I8i8sbyte
U8u8byte
I16i16short
U16u16ushort
I32i32int
U32u32uint
I64i64long
U64u64ulong
Boolboolbool
EntityEntityulong, read and never written

A struct inside the component is flattened into its fields under dotted names: Bevy's Vec3 field offset is offset.x, offset.y and offset.z, and a Transform's position is translation.x. A fixed-size array, such as [u32; 2], is one field with a Count of 2.

What is left out. A field of any other kind, such as an asset Handle, a String, a Vec, or a u128, has no offset to read and is not in the layout. Enums are not in it either; they are read and written whole, as Enums shows. A component with nothing describable comes back with no fields, and can still be queried for. world.TraitsOf(layout.Id) has ComponentTraits.Partial set for a component part of which is left out.

Entities. Bevy's ChildOf, an entity's parent, holds an Entity. It is read as the number C# knows an entity by, and never written: a parent is changed only through commands, which keep the hierarchy whole, so the layout of a component holding one refuses Write(). See Reading parents.

Reading and writing fields in a system

Query the component with its layout's terms, and read each field through a FieldView<T>, whose T must match the field's kind:

ComponentLayout light = world.LayoutOf("PointLight");ComponentField range = light["range"];ComponentType<Pulse> pulse = world.Component<Pulse>();
schedule.Add("Pulse lights", [light.Write(), pulse.Write()], context =>{    foreach (Chunk chunk in context.Chunks)    {        FieldView<float> ranges = chunk.GetFieldView<float>(0, range);        Span<Pulse> pulses = chunk.GetSpan<Pulse>(1);        for (int row = 0; row < ranges.Length; row++)        {            pulses[row].Phase += pulses[row].Speed * context.DeltaTime;            ranges[row] = pulses[row].Reach * (0.75f + (0.25f * MathF.Sin(pulses[row].Phase)));        }    }});

view[row] is a ref to the field's value in that row. For an array field, view[row, element] reaches one value, and CopyRowTo(row, span) and CopyRowFrom(row, span) copy a row's values at once. A view of a column declared with Read() refuses writes, and IsWritable says which it is.

A whole row of such a component cannot be written as bytes: GetSpan refuses it, because bytes C# chooses may not be a valid value of a type that holds a handle, an enum or a string. Only components declared in C# and the engine's own, such as Transform, are plain data that way (ComponentTraits.PlainData). GetReadOnlySpan reads the bytes of any component.

It is slower than a span. A column holds whole components back to back, so one field's values are Size bytes apart, not side by side, and a view walks them one stride at a time. For data you control, a component declared in C# is still the fastest to loop over.

Bevy sees what C# writes. A system that writes a component with a Rust type publishes Bevy's change ticks for it, so a Rust system with Changed<T> sees the write. See Reacting to changes.

Between frames

Code that runs between frames, such as a flow or a plugin's hook, reads and writes one entity's component through the world:

ComponentLayout light = world.LayoutOf("PointLight");ComponentField range = light["range"];
world.WriteComponent(lamp, light.Id, range.Offset, BitConverter.GetBytes(12f));
byte[] held = new byte[light.Size];world.ReadComponent(lamp, light.Id, held);float now = BitConverter.ToSingle(held.AsSpan(range.Offset));

ReadComponent copies the whole value, which is safe for any component. WriteComponent is refused unless the bytes land entirely inside one field the engine describes, or the component was declared in C#: not even the padding between two fields may be written. A write is published through Bevy's change detection, as a system's is.

Enums

An enum is never read at an offset: where a Rust enum keeps which variant it holds, and where each variant's fields are, is the compiler's choice. The engine reads and writes enums whole, through Bevy's reflection, their values written as JSON the way Bevy writes them: "Hidden" for a Visibility, or {"Srgba":{"red":1.0,"green":0.5,"blue":0.2,"alpha":1.0}} for a color.

ComponentLayout light = world.LayoutOf("PointLight");
IReadOnlyDictionary<string, string> held = world.ChoicesIn(lamp, light.Id);   // "color" and its valueworld.SetChoice(lamp, light.Id, "color", """{"Srgba":{"red":1.0,"green":0.5,"blue":0.2,"alpha":1.0}}""");

world.ChoicesOf(id) lists the enums a component holds, each a ComponentChoice with its Path, empty for a component that is an enum itself, and its Variants, each with its Name and the Value choosing it gives. A value given to SetChoice may leave fields out: the variant keeps what it held of them, or starts another from its defaults. An enum that can hold an entity is not reachable this way. SetChoice marks the component changed, so Changed<T> sees it too.

Putting one on an entity

A command buffer carries values as bytes, so it cannot spawn an entity with, or give it, a component of Bevy's, a plugin's or your crate's: only those declared in C# and the engine's own. Put one on between frames instead:

ComponentId pointLight = world.ComponentByName("PointLight")!.Value;world.AddComponent(lamp, pointLight);   // its own default value, with what it requires

AddComponent gives the type's own default, through Bevy's type registry, and whatever the type requires comes with it, as Add Component does in the Inspector: a light brings the Transform it cannot be drawn without. It returns false, changing nothing, for an entity that has the component already, and throws for a Rust type without #[reflect(Component, Default)]. Write its fields afterward. world.RemoveComponent(entity, id) takes it off again, leaving what it required.

Both change which components the entity carries at once, so chunks resolved before them go stale: call them from a flow or a hook, not inside a system's loop.

Finding out what an entity carries

The Inspector is built on these same calls, and names no component itself: it asks the entity what it carries, asks the engine what each component is called and where its fields are, and reads each field at its offset. So a component from a Bevy plugin, or one written after the editor was, is shown the way Transform is: its described fields as rows, structs flattened, enums as lists, and what cannot be described left out. The Debug view shows every component the entity carries, the engine's bookkeeping included.

Your code can do the same:

CallWhat it gives
world.ComponentsOf(entity)The ids of the components it carries, in a stable order.
world.NameOf(id)The shortest name that finds the component again: Transform, or a full path where two types share a name.
world.LayoutOf(id)Its layout, or null where the engine describes none of it.
world.ChoicesOf(id)The enums it holds.
world.TraitsOf(id)Whether it has a Rust type (Rust), can be made from bytes (PlainData), is the engine's own (Engine), is worked out by Bevy (Computed), can be added (CanBeAdded) or is only partly described (Partial).
world.ReadComponent(entity, id, bytes)Its value, as bytes.
world.EntityName(entity)The entity's name, or null.
foreach (ComponentId id in world.ComponentsOf(entity)){    string name = world.NameOf(id);    if (world.LayoutOf(id) is not { Size: > 0 } layout)    {        Log.Info(name);        continue;    }
    byte[] bytes = new byte[layout.Size];    world.ReadComponent(entity, id, bytes);    foreach (ComponentField field in layout.Fields)    {        if (field.Kind == FieldKind.F32 && field.Count == 1)        {            Log.Info($"{name}.{field.Name} = {BitConverter.ToSingle(bytes.AsSpan(field.Offset))}");        }    }}

world.Entities(skip, rows, out int total) lists the world's entities a page at a time, each an EntityRow with its id, its parent, its scene and its components' archetype. It walks and sorts every entity in the world, the engine's own included, so it is for a tool or a debug screen, not for every frame.

In the Scripting API