Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Migrating from 0.23 to 0.24

See the release notes for what’s new. Most important changes first.

Scripts

Rhai is removed

Port Rhai scripts to Lua, or to Rune (the rune feature).

Everything is imported

The only globals left are import_namespace, export_namespace and register_callback. Everything else, world and types included, is imported from a namespace, see Namespaces. Bevy types are grouped by category (math, ecs, transform, ui, …), BMS’ types and functions live in bms:

+ local bms = import_namespace("bms")
+ local world = bms.world
+ local Vec3 = import_namespace("math").Vec3
+ local Transform = import_namespace("transform").Transform
  local t = Transform.from_translation(Vec3.new(1, 2, 3))
- log_info("hi")
+ bms.log_info("hi")
- world.despawn(entity)
+ world.despawn(bms.current_entity())
- script_asset
+ bms.current_script()

construct, system_builder, run_script_callback, queue_script_callback, pack_args and unpack_args moved to bms the same way. The deprecated types table is removed.

Query results are lists

The entity followed by the components, in the order they were added to the query:

  for _, result in pairs(world.query():component(Transform):build()) do
-     local entity, transform = result:entity(), result:components()[1]
+     local entity, transform = result[1], result[2]
  end

Other changes

  • The bindings are hand-written: functions of Bevy types which were generated before may be missing or named differently, check the generated docs.
  • world.get_type_by_name only takes full paths, i.e. "bevy_transform::components::transform::Transform" or "script.my_game.Enemy".
  • Script systems: resource and query components are writes, systems writing the same data no longer run in parallel, use resource_read / component_read where you only read. Sets are values (world.register_new_system_set(namespace, name), world.get_system_set_by_name) instead of names.
  • Asset references can’t be used in non-exclusive script systems, nor together with a mutably borrowed component in the same call.
  • Lua’s math.random is seeded with 0 in new contexts, and callbacks reach scripts in attachment order, see Determinism.

Rust

Features and crates

  • The rhai feature and bevy_mod_scripting_rhai are removed.

  • The generated *_bms_bindings crates are replaced by bevy_mod_scripting_bevy_<category>_bindings. The binding features are now bevy_{animation, asset, audio, camera, color, ecs, gizmos, input, math, render, sprite, state, text, time, transform, ui, window}_bindings:

    0.23 feature0.24
    bevy_reflect_bindings, bevy_curve_bindings, bevy_shape_bindingsbevy_math_bindings
    bevy_image_bindings, bevy_mesh_bindings, bevy_pbr_bindingsbevy_render_bindings
    bevy_input_focus_bindingsbevy_input_bindings
    bevy_core_pipeline_bindings, bevy_gltf_bindings, bevy_light_bindings, bevy_picking_bindings, bevy_post_process_bindings, bevy_scene_bindings, bevy_sprite_render_bindings, bevy_ui_render_bindings, bevy_ui_widgets_bindingsremoved, reachable through reflection

    The default features are core_functions and the ecs, input, math, time, transform, color and window bindings.

  • mlua is bumped to 0.12, see its changelog if you use it directly.

Script globals are removed

AppScriptGlobalsRegistry, #[script_globals], register_static*, GlobalNamespace, FunctionScope::Global, DummyScriptFunctionRegistry and use_dummy_registry are gone. Put functions in a namespace instead:

#[script_bindings(remote, namespace = "my_game")]
impl NamespaceMembers {
    /// `import_namespace("my_game").spawn_enemy(5)` in scripts
    fn spawn_enemy(ctxt: FunctionCallContext, hp: usize) -> Result<(), InteropError> { .. }
}

Values go in AppScriptNamespaceMembers::register_value, made each time the namespace is imported. Types with bindings from the bevy crates are in category namespaces, move a type with app.override_script_namespace.

Borrowed arguments end with the call

FromScript::from_script takes a &CallScope instead of a WorldGuard, and R/M borrow from it, so they can’t be kept past the function call (M<'static, T> arguments no longer compile). Get the guard with scope.world(), and convert outside of script functions in guard.with_call_scope(|scope| ..), which replaces with_access_scope and releases the claims when it ends:

fn from_script<'s>(value: ScriptValue, scope: &'s CallScope<'_>) -> Result<Self::This<'s>, InteropError> {
    let world = scope.world();
    ..
}

The allocator is removed

Values allocated for scripts are owned by the references to them and freed with the last one. ReflectAllocator, AppReflectAllocator, WorldExtensions::allocator, AllocatorDiagnosticPlugin, ScriptingSystemSet::GarbageCollection and InteropError::GarbageCollectedAllocation are gone, drop the allocator argument:

- let reference = ReflectReference::new_allocated(value, &mut world.allocator().write());
+ let reference = ReflectReference::new_allocated(value);

new_allocated_boxed and new_allocated_boxed_partial_reflect (renamed from new_allocated_boxed_parial_reflect) change the same way.

Functions

  • Registering a function name twice replaces it, there are no overloads (overwrite*, iter_overloads, remove_all_overloads are removed). Take a Union or ScriptValue for arguments of different types.
  • ScriptFunctionRegistry is keyed by TypeId instead of a namespace: register(type_id, ..), get_function(type_id, name), iter_namespace → iter_type.
  • #[derive(ScriptType)] implements everything a type needs to be used directly in function signatures (FromScript, IntoScript, ArgMeta, GetTypeDependencies, TypedThrough). Use #[script_type(from = custom)] / (into = custom) for a hand written conversion.
  • Renames: Namespace → FunctionScope (IntoNamespace is removed, use FunctionScope::OnType(TypeId::of::<T>())), FromScriptRef/IntoScriptRef → FromScriptErased/IntoScriptErased, try_call_overloads → call_operator.
  • Functions on StaticTypeRef take StaticTypeRef instead of V<StaticTypeRef>.

Script pipeline

  • ScriptAttachedMessage(a) / ScriptDetachedMessage(a) are one message, ScriptLifecycleMessage::Attached(a) / ::Detached(a), processed in the order they were written. An attachment whose script is still loading holds back the ones after it.
  • LoadedWithHandles is ScriptLifecycleQueue, get_ready yields (event, Option<(StrongScriptHandle, Language)>). GetScriptHandle::get_script_handle returns an Option (None: the event doesn’t wait for its script to load).
  • ScriptLoadingPipeline::time_budget: Option<Duration> is replaced by tick_budget: Option<usize>, the maximum amount of pipeline steps per frame, unlimited by default. ActiveMachines::budget and RunProcessingPipelineOnce::new take the same step count.

Script systems

  • Systems are identified by attachment and callback label (adding one again replaces it) and are removed with their script. Their errors are sent as ScriptErrorMessages instead of being logged.
  • ScriptSystemBuilder no longer implements IntoSystem, use ScriptSystemBuilder::build. in_set, before_set and after_set take a SystemSet. ScriptSystemSet holds a recycled slot instead of the callback label.
  • Rust sets are exposed to scripts with app.register_script_system_set(namespace, name, set) (ScriptSystemSetAppExt, now in bevy_mod_scripting_bindings). ReflectSystemSet is opaque.
  • ScriptQueryBuilder::as_query_state takes a QueryAccess: Declared for queries reported to the scheduler, MatchOnly for queries only finding entities.
  • ScriptQueryResult converts to a list instead of a reference, and its components are a Vec<Option<ReflectReference>>, None for absent optional components.

World access

  • ReflectReference::new_component_ref_by_id / new_resource_ref_by_id, ScriptComponentRegistration::new and ScriptResourceRegistration::new are unsafe: the type must be the type of the component or resource id. ReflectBaseType::base_id is private, read it with base_id().
  • WorldAccessGuard::new_non_exclusive takes an Option<Arc<ArchetypeFilter>>, restricting component accesses to the given archetypes (None for no restriction).
  • WorldAccessRange::External holds the value itself (AccessOwner) instead of an id and is no longer Copy, build it from the value: (&allocation_id).into().
  • At most 63 accesses to the same value can be claimed at once, claims beyond fail (the count used to overflow).
  • Asset references claim global access, and reading an asset no longer marks it modified.
  • ThreadWorldContainer::try_get_context() is an associated function (was ThreadWorldContainer.try_get_context()), set_context is replaced by replace_context, which restores the previous context when its guard is dropped. set_cached_registry is replaced by replace_cached_registry.
  • Removed: DynamicSystemMeta and its with_scope / release_all_accesses (claims are released when their CallScope ends), WorldAccessGuard::release_all_accesses, with_world_access_and_then, as_unsafe_world_cell_readonly (use as_unsafe_world_cell).
  • ReflectReference::type_id_of and TypeIdSource are removed, use tail_type_id, element_type_id or key_type_id.
  • ReferencePath::set_is_one_indexed is removed: indexes are normalised when the path is created.

Language implementations

  • Dispatch every script operation through bevy_mod_scripting_bindings::dispatch (index, set_index, static_index, binary, unary, len, iter, display, debug), see Necessary Features. WorldExtensions::lookup_function, lookup_instance_function, lookup_type_function and lookup_reserved_function are private.
  • Convert the new ScriptValue::Type(TypeId), a type itself (what world and StaticTypeRef are).
  • Set bindings::builtins::builtins() (import_namespace, export_namespace) and your register_callback as globals, nothing else. Don’t set world, entity or script_asset anymore.
  • LuaStaticReflectReference is LuaTypeRef.

Documentation tooling

  • The Lua language server files are split per namespace (bindings.d.lua, bindings.<namespace>.d.lua): point workspace.library at the directory. Classes are named after their namespace (math.Vec3), and generic classes need LuaLS 3.17+.
  • cargo xtask docgen is replaced by cargo xtask docs (all binding features, --test-bindings for the script test functions). cargo xtask bless-lad updates the LAD test fixtures.
  • ThroughTypeInfo is flat (ThroughTypeInfo::Vec(..), ThroughTypeInfo::Ref(type_info), replacing TypedWrapper / UntypedWrapper), ThroughTypeInfo::TypeInfo is Opaque. #[derive(TypedThrough)] documents a type as opaque, #[typed_through(value)] as a value.
  • generate_lad_file takes the AppGenericTypes, see app.register_generic_type.
  • LAD format:
    • LadFieldOrVariableKind → LadTypeKind. Ref/Mut/Val hold a LadNamedType: a type id as before, or a generic type applied to arguments ({ "generic_type": "bevy_asset::handle::Handle", "args": [...] }).
    • globals is removed, builtin functions are LadFunctionNamespace::Global (the mdbook “Globals” and “Functions” pages are one “Builtins” page). Namespaces have values (add_instance* → add_namespace_value_of / add_namespace_instance).
    • Instantiations of declared generic types are recorded on the generic type (generic_types, LadGenericType::instantiations, LadFile::get_instantiation) instead of being types of the file. polymorphizied_types is removed.
    • LadFunctionMetadata::is_operator → operator. Arguments are always named and never include the call context.
    • ArgumentVisitor has an Output type and visit_* methods per kind (visit_generic, visit_type, visit_tuple_with_rest, …).