Custom Inspector Fields
How the Inspector is driven by a registry of declarative field definitions, and how to make your own components editable: the derive, hand-written fields, groups and custom drawers.
The model
The Inspector is data-driven. Each component type registers an InspectorEntry (a name, icon, category and a list of FieldDefs) in the InspectorRegistry resource. A FieldDef is a label, a FieldType that picks the widget, and a pair of plain function pointers:
pub struct FieldDef {
pub name: &'static str,
pub field_type: FieldType,
pub get_fn: fn(&World, Entity) -> Option<FieldValue>,
pub set_fn: fn(&mut World, Entity, FieldValue),
}
renzora_inspector walks the registry for the selected entity, binds each field's widget to its get_fn and writes edits back through set_fn. Returning None from get_fn hides the row, which is how a field that only applies sometimes disappears.
Function pointers rather than closures keep the entries Clone and free of captured state, and keep the contract (renzora_editor_api, in crates/api/) free of any UI dependency. The cost is that the Inspector cannot see what a get_fn reads; see Declaring what a section reads.
Dependencies
An engine crate depends on the contract directly:
[dependencies]
bevy = { workspace = true }
renzora_editor_api = { path = "../api/renzora_editor_api" }
There is no prelude: import what you use, as in use renzora_editor_api::{AppEditorExt, Inspectable};. A native plugin reaches the same items as renzora::Inspectable, renzora::AppEditorExt and so on. The derive emits paths to ::renzora_editor_api when the crate's package name starts with renzora_, and to ::renzora otherwise.
The fast path: #[derive(Inspectable)]
use bevy::prelude::*;
use renzora_editor_api::{AppEditorExt, Inspectable};
#[derive(Component, Default, Reflect, Inspectable)]
#[inspectable(name = "Health", icon = "HEART", category = "scripting")]
pub struct Health {
#[field(speed = 1.0, min = 0.0, max = 10000.0)]
pub current: f32,
#[field(speed = 1.0, min = 1.0, max = 10000.0)]
pub max: f32,
#[field(name = "Shield")]
pub has_shield: bool,
}
#[derive(Default)]
pub struct HealthInspectorPlugin;
impl Plugin for HealthInspectorPlugin {
fn build(&self, app: &mut App) {
app.register_inspectable::<Health>();
}
}
register_inspectable::<T>() calls register_type::<T>() (so reflection and scenes can reach the component), registers T::inspector_entry(), and declares that the section reads only T (see below). T must implement InspectableComponent (which the derive provides and which needs Component + Default) and GetTypeRegistration (from Reflect).
#[inspectable(...)]
| Attribute | Default | Effect |
|---|---|---|
name | the struct name, title-cased | Section header |
icon | "CUBE" | A Phosphor constant name in SCREAMING_SNAKE_CASE, emitted as kebab case (SNEAKER_MOVE becomes sneaker-move) |
category | "object" | The Inspector page the section appears on, and its Add Component group |
type_id | the struct name, snake_case | The entry's stable key in the registry |
The pages are object, rendering, lighting, camera, environment, post_process, physics, animation, scripting, audio, navigation, networking, ui and particles (renzora_shell_api::inspector_pages). An older category name such as gameplay is mapped onto a page, so it still lands somewhere sensible.
#[field(...)]
| Attribute | Applies to | Effect |
|---|---|---|
speed | f32 (default 0.01), Vec3 (default 0.1) | Drag sensitivity |
min, max | f32 (defaults f32::MIN, f32::MAX) | Clamp |
name | any | Row label (default: the field name, title-cased) |
skip | any | Leave the field out |
readonly | any | Show a non-editable {:?} string |
default | none | Parsed and ignored. Initial values come from the type's Default, which Add Component inserts. |
Field types the derive understands
| Rust type | FieldType |
|---|---|
f32 | Float { speed, min, max } |
bool | Bool |
Vec3 | Vec3 { speed } |
String | String |
Color | Color (RGB) |
| anything else | ReadOnly (a {:?} string) |
Integers, f64, Vec2, enums, Entity and Handle<_> are not editable through the derive. Integers come out as ReadOnly; an f64 field does not compile, because the generated getter builds a FieldValue::Float(f32) from it. Use the macros below for those, or mark the field skip.
Two more rules: the derive accepts only structs with named fields, and it skips fields named enabled or starting with _p (the post-process settings convention, where enabled is the section's own switch).
A component that also ships in games
A crate whose plugin is runtime scope runs in the shipped game, which has no inspector. Make the contract optional and gate everything editor-side on a feature of your own. renzora_ik is the worked example:
[dependencies]
renzora_editor_api = { path = "../api/renzora_editor_api", optional = true }
[features]
default = ["editor"]
editor = ["dep:renzora_editor_api"]
// Simplified from crates/renzora_ik/src/components.rs and lib.rs.
#[derive(Component, Reflect, Clone, Debug)]
#[cfg_attr(feature = "editor", derive(renzora_editor_api::Inspectable))]
#[reflect(Component, Default)]
#[cfg_attr(feature = "editor", inspectable(name = "Two Bone IK", icon = "BONE", category = "animation"))]
pub struct TwoBoneIk {
#[cfg_attr(feature = "editor", field(name = "Weight", speed = 0.01, min = 0.0, max = 1.0))]
pub weight: f32,
// ...
}
impl Plugin for IkPlugin {
fn build(&self, app: &mut App) {
app.register_type::<TwoBoneIk>();
#[cfg(feature = "editor")]
{
use renzora_editor_api::AppEditorExt;
app.register_inspectable::<TwoBoneIk>();
}
}
}
With the feature off, the derive, its InspectableComponent impl and the registration all disappear, and the component is a plain runtime type.
Hand-written fields
For what the derive cannot map, build FieldDefs with the field macros (exported at the root of renzora_editor_api, and of renzora for plugins) and register the entry yourself:
| Macro | Field type | Widget |
|---|---|---|
float_field!(name, Comp, field, speed, min, max) | f32 | Drag value |
int_field!(name, Comp, field, ty, speed, min, max) | any integer ty | Drag value; the f32 is cast with as ty on write |
bool_field!(name, Comp, field) | bool | Checkbox |
string_field!(name, Comp, field) | String | Text input |
color_rgba_field!(name, Comp, field) | Color | Colour picker with alpha |
vec3_color_field!(name, Comp, field) | Vec3 holding RGB | Colour picker |
tuple_color_field!(name, Comp, field) | (f32, f32, f32) | Colour picker |
enum_u32_field!(name, Comp, field, ["A", "B", ...]) | u32 index | Dropdown |
use bevy::prelude::*;
use renzora_editor_api::{
enum_u32_field, int_field, AppEditorExt, FieldDef, FieldType, FieldValue, InspectorEntry,
};
#[derive(Component, Default, Reflect)]
pub struct SpawnConfig {
pub max_entities: u32,
pub mode: u32,
pub spawn_rate: f32,
}
fn register_spawn_config(app: &mut App) {
app.register_type::<SpawnConfig>();
app.register_inspector(InspectorEntry {
type_id: "spawn_config",
display_name: "Spawn Config",
icon: "sparkle", // kebab case here: this is the glyph name itself
category: "scripting",
has_fn: |w, e| w.get::<SpawnConfig>(e).is_some(),
add_fn: Some(|w, e| {
w.entity_mut(e).insert(SpawnConfig::default());
}),
remove_fn: Some(|w, e| {
w.entity_mut(e).remove::<SpawnConfig>();
}),
is_enabled_fn: None,
set_enabled_fn: None,
fields: vec![
int_field!("Max Entities", SpawnConfig, max_entities, u32, 1.0, 0.0, 10000.0),
enum_u32_field!("Mode", SpawnConfig, mode, ["Burst", "Stream", "Trickle"]),
FieldDef {
name: "Spawn Rate",
field_type: FieldType::Float { speed: 0.1, min: 0.0, max: 100.0 },
get_fn: |w, e| w.get::<SpawnConfig>(e).map(|c| FieldValue::Float(c.spawn_rate)),
set_fn: |w, e, v| {
if let (FieldValue::Float(f), Some(mut c)) = (v, w.get_mut::<SpawnConfig>(e)) {
c.spawn_rate = f;
}
},
},
],
});
// Every field above reads SpawnConfig on this entity and nothing else.
app.inspector_reads::<SpawnConfig>("spawn_config");
}
add_fn being Some is what lists the component in Add Component; remove_fn adds the remove button. is_enabled_fn and set_enabled_fn together give the section header an on/off switch. Leave them None for a read-only section.
InspectorRegistry::register pins transform first and material_ref second, and keeps everything else in registration order. Registering a type_id again replaces the earlier entry in place.
Adding rows to someone else's section
app.extend_inspector(type_id, fields) appends fields to another crate's entry (inserted above a trailing button, if it has one). Use it when your crate adds a setting to a component it does not own, instead of making the owner depend on you.
Declaring what a section reads
Each row is a live binding to its get_fn. Because a get_fn is a plain function pointer, the Inspector cannot see what it reads, so an undeclared section runs every field on every frame. That is always correct, just not free. app.inspector_reads::<C>("type_id") (or InspectorRegistry::reads::<C>) tells it, and the section's fields then run only on a frame where a declared component changed on that entity. See Reactivity for how that is wired.
- Declare each component any of the section's fields, or its enable switch, reads. Several calls stack.
- Declare only when every field reads nothing else: no resource, no asset, no other entity. A field that also reads something undeclared would stop updating when only that thing changes. When in doubt, leave it out.
register_inspectable::<T>()declaresTfor you.- Rows added with
extend_inspectorare never covered by the section's declaration, since they read their own components.
Grouping fields
A long section reads better with related settings folded away:
use renzora_editor_api::{bool_field, float_field, int_field, FieldDef};
fields: vec![
float_field!("Intensity", MySettings, intensity, 0.01, 0.0, 8.0),
FieldDef::group("Advanced", vec![
float_field!("Bias", MySettings, bias, 0.001, 0.0, 1.0),
int_field!("Steps", MySettings, steps, u32, 1.0, 4.0, 64.0),
]),
// The header is the feature's on/off switch.
FieldDef::toggle_group(
bool_field!("Fog", MySettings, fog),
vec![float_field!("Density", MySettings, fog_density, 0.001, 0.0, 1.0)],
),
],
The group's own get_fn decides its header:
get_fn returns | Header |
|---|---|
None | the whole group is hidden |
Some(FieldValue::Bool(_)) | caret, name and an on/off switch written through set_fn (what toggle_group builds) |
| anything else | caret and name (what group builds) |
Groups start folded, and the Inspector remembers per component type and group name which ones the user opened. A folded group builds none of its rows, which saves their layout every frame, not just screen space.
Custom drawers
When declarative fields are not enough (conditional rows, previews, a bespoke layout), register a drawer that builds an arbitrary bevy_ui subtree for the section:
use bevy::ecs::world::CommandQueue;
use bevy::prelude::*;
use renzora_editor_api::AppEditorExt;
// NativeInspectorDrawer = fn(&mut World, Entity) -> Entity
fn draw_spawn_config(world: &mut World, entity: Entity) -> Entity {
let mut queue = CommandQueue::default();
let root = {
let mut commands = Commands::new(&mut queue, world);
let root = commands.spawn(Node { flex_direction: FlexDirection::Column, ..default() }).id();
// Build ember widgets and bindings here, reading `entity`.
root
};
queue.apply(world);
root
}
fn register(app: &mut App) {
app.register_native_inspector_ui("spawn_config", draw_spawn_config);
}
The drawer returns the root entity, and the Inspector parents it under the section header. Read the world through bindings (see Reactivity) and write it from interaction handlers.
Write a drawer to be called many times. A section body is built only while the section is expanded and on screen (within half a viewport, at least 200 px, of the visible area), and its rows are despawned when it is collapsed or scrolled away. So a drawer runs on every expand and every scroll back into view, not once per selection. Keep state that must survive in a Resource, and keep one-time setup out of the drawer.
The reason is layout cost: bevy_ui does not skip Display::None subtrees in its per-frame walk, so a hidden or off-screen row costs as much layout as a visible one. Collapsing a section was measured at about 3.3 ms a frame saved for one entity's worth of open components. The decisions are made in renzora_inspector::panel::section::reconcile_section_bodies (build and tear down) and panel::cull::cull_offscreen_sections (which sets the on-screen flag it reads).
Reference
FieldType
| Variant | Value type | Notes |
|---|---|---|
Float { speed, min, max } | Float | |
Int { min, max } | Float | The widget snaps to whole numbers. Use it for a set_fn that rounds into an integer, or the drag and the rounded re-read fight each other. |
Vec3 { speed } | Vec3 | |
Bool | Bool | |
Color, ColorRgba | Color, ColorRgba | RGB, and RGB with editable alpha |
String | String | |
ReadOnly | ReadOnly | |
Asset { extensions } | Asset | Accepts a drop from the asset browser; an empty list accepts any file |
AssetCreatable { extensions, create_fn } | Asset | Adds a + button that creates and assigns a new asset while the field is empty |
Enum { options } | Enum | set_fn receives the selected label |
DynamicEnum { options } | Float (index) | Options computed by fn(&World, Entity) -> Vec<String> |
CheckedEnum { options, warning } | Enum | warning(world, entity, index) returning Some(reason) marks an option with an amber warning; it stays selectable |
Button { icon } | none | A full-width action. get_fn returns None (or Some(Bool(false)) to hide); a click calls set_fn with Bool(true) |
Group { fields } | see above | Build with FieldDef::group or FieldDef::toggle_group |
FieldValue
pub enum FieldValue {
Float(f32),
Vec3([f32; 3]),
Bool(bool),
Color([f32; 3]),
ColorRgba([f32; 4]),
String(String),
ReadOnly(String),
Asset(Option<String>),
Enum(String),
}
InspectorEntry
pub struct InspectorEntry {
pub type_id: &'static str,
pub display_name: &'static str,
pub icon: &'static str, // kebab-case Phosphor name
pub category: &'static str,
pub has_fn: fn(&World, Entity) -> bool,
pub add_fn: Option<fn(&mut World, Entity)>,
pub remove_fn: Option<fn(&mut World, Entity)>,
pub is_enabled_fn: Option<fn(&World, Entity) -> bool>,
pub set_enabled_fn: Option<fn(&mut World, Entity, bool)>,
pub fields: Vec<FieldDef>,
}
Not everything is a section
The entity's id, icon, hierarchy label colour and visibility are drawn by the Inspector's fixed entity header (renzora_inspector::entity_header), not by registry entries: none of them is a component you add or remove. Something that describes the entity rather than a component on it belongs there. The authored parts (EntityIcon, EntityLabelColor) live in the contract, so they serialize into the scene.
For where these registrations fit among the editor's other extension points, see Editor API.