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_nameonly takes full paths, i.e."bevy_transform::components::transform::Transform"or"script.my_game.Enemy".- Script systems:
resourceand querycomponents are writes, systems writing the same data no longer run in parallel, useresource_read/component_readwhere 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.randomis seeded with0in new contexts, and callbacks reach scripts in attachment order, see Determinism.
Rust
Features and crates
-
The
rhaifeature andbevy_mod_scripting_rhaiare removed. -
The generated
*_bms_bindingscrates are replaced bybevy_mod_scripting_bevy_<category>_bindings. The binding features are nowbevy_{animation, asset, audio, camera, color, ecs, gizmos, input, math, render, sprite, state, text, time, transform, ui, window}_bindings:0.23 feature 0.24 bevy_reflect_bindings,bevy_curve_bindings,bevy_shape_bindingsbevy_math_bindingsbevy_image_bindings,bevy_mesh_bindings,bevy_pbr_bindingsbevy_render_bindingsbevy_input_focus_bindingsbevy_input_bindingsbevy_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_functionsand theecs,input,math,time,transform,colorandwindowbindings. -
mluais 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_overloadsare removed). Take aUnionorScriptValuefor arguments of different types. ScriptFunctionRegistryis keyed byTypeIdinstead 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(IntoNamespaceis removed, useFunctionScope::OnType(TypeId::of::<T>())),FromScriptRef/IntoScriptRef→FromScriptErased/IntoScriptErased,try_call_overloads→call_operator. - Functions on
StaticTypeReftakeStaticTypeRefinstead ofV<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.LoadedWithHandlesisScriptLifecycleQueue,get_readyyields(event, Option<(StrongScriptHandle, Language)>).GetScriptHandle::get_script_handlereturns anOption(None: the event doesn’t wait for its script to load).ScriptLoadingPipeline::time_budget: Option<Duration>is replaced bytick_budget: Option<usize>, the maximum amount of pipeline steps per frame, unlimited by default.ActiveMachines::budgetandRunProcessingPipelineOnce::newtake 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. ScriptSystemBuilderno longer implementsIntoSystem, useScriptSystemBuilder::build.in_set,before_setandafter_settake aSystemSet.ScriptSystemSetholds 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 inbevy_mod_scripting_bindings).ReflectSystemSetis opaque. ScriptQueryBuilder::as_query_statetakes aQueryAccess:Declaredfor queries reported to the scheduler,MatchOnlyfor queries only finding entities.ScriptQueryResultconverts to a list instead of a reference, and itscomponentsare aVec<Option<ReflectReference>>,Nonefor absent optional components.
World access
ReflectReference::new_component_ref_by_id/new_resource_ref_by_id,ScriptComponentRegistration::newandScriptResourceRegistration::newareunsafe: the type must be the type of the component or resource id.ReflectBaseType::base_idis private, read it withbase_id().WorldAccessGuard::new_non_exclusivetakes anOption<Arc<ArchetypeFilter>>, restricting component accesses to the given archetypes (Nonefor no restriction).WorldAccessRange::Externalholds the value itself (AccessOwner) instead of an id and is no longerCopy, 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 (wasThreadWorldContainer.try_get_context()),set_contextis replaced byreplace_context, which restores the previous context when its guard is dropped.set_cached_registryis replaced byreplace_cached_registry.- Removed:
DynamicSystemMetaand itswith_scope/release_all_accesses(claims are released when theirCallScopeends),WorldAccessGuard::release_all_accesses,with_world_access_and_then,as_unsafe_world_cell_readonly(useas_unsafe_world_cell). ReflectReference::type_id_ofandTypeIdSourceare removed, usetail_type_id,element_type_idorkey_type_id.ReferencePath::set_is_one_indexedis 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_functionandlookup_reserved_functionare private. - Convert the new
ScriptValue::Type(TypeId), a type itself (whatworldandStaticTypeRefare). - Set
bindings::builtins::builtins()(import_namespace,export_namespace) and yourregister_callbackas globals, nothing else. Don’t setworld,entityorscript_assetanymore. LuaStaticReflectReferenceisLuaTypeRef.
Documentation tooling
- The Lua language server files are split per namespace (
bindings.d.lua,bindings.<namespace>.d.lua): pointworkspace.libraryat the directory. Classes are named after their namespace (math.Vec3), and generic classes need LuaLS 3.17+. cargo xtask docgenis replaced bycargo xtask docs(all binding features,--test-bindingsfor the script test functions).cargo xtask bless-ladupdates the LAD test fixtures.ThroughTypeInfois flat (ThroughTypeInfo::Vec(..),ThroughTypeInfo::Ref(type_info), replacingTypedWrapper/UntypedWrapper),ThroughTypeInfo::TypeInfoisOpaque.#[derive(TypedThrough)]documents a type as opaque,#[typed_through(value)]as a value.generate_lad_filetakes theAppGenericTypes, seeapp.register_generic_type.- LAD format:
LadFieldOrVariableKind→LadTypeKind.Ref/Mut/Valhold aLadNamedType: a type id as before, or a generic type applied to arguments ({ "generic_type": "bevy_asset::handle::Handle", "args": [...] }).globalsis removed, builtin functions areLadFunctionNamespace::Global(the mdbook “Globals” and “Functions” pages are one “Builtins” page). Namespaces havevalues(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_typesis removed. LadFunctionMetadata::is_operator→operator. Arguments are always named and never include the call context.ArgumentVisitorhas anOutputtype andvisit_*methods per kind (visit_generic,visit_type,visit_tuple_with_rest, …).