Hazel

Scripting with Rust

Scripts are how your game does things: a door that opens, a coin that spins, a player that moves when you press a key. In Renzora you write them in Rust, using Bevy, the engine library Renzora is built on.

You do not need to set up a Rust project, a Cargo.toml or a build command. You write one .rs file, save it, and the editor compiles it for you in the background.

This page is a hands-on guide. For every detail, see the Rust scripts reference.

A Rust script, spin.rs, open in the Code Editor

Before you start: install Rust

Scripts are compiled on your computer, so the editor needs Rust installed. If it is missing, the start screen shows a strip across the top with an Install Rust button. Click it and keep working; it takes a few minutes (about 400 MB). The strip turns green when it is done.

If you open a project that has scripts without installing first, the editor asks once more with an Install Rust? prompt. Not now lets you carry on, but scripts will not compile until Rust is there.

Players of your finished game never need Rust. The editor compiles your scripts into the game when you export it.

Create a script

There are two ways.

From the Assets panel. Open the folder you want the script in, click Import (or right-click an empty spot in the panel), and pick Rust Script under Create Asset. You get new_script.rs, ready to rename.

The Import window, with Rust Script under Create Asset

From the Hierarchy. Right-click the entity that should own the script, choose Attach, then Rust Script. Give it a name, pick a folder, and click Create. The script is created and attached in one step.

The Hierarchy's right-click menu with Attach highlighted

A new script already works. It looks like this:

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let dt = ctx.delta();
    if let Some(mut transform) = ctx.get_mut::<Transform>() {
        transform.rotate_y(dt);
    }
}

renzora::script!(update);

Three parts to know:

  • fn update runs once every frame, for every entity the script is attached to. You can call it anything.
  • ctx is your handle on the entity the script is attached to, and on the rest of the game.
  • renzora::script!(update); tells the engine which function to run. Leave it out and the script builds, then fails to load with "exports no entry point".

Scripts can live anywhere in your project folder. Put one beside the model it drives if that helps you find it.

Attach a script

Every entity has a Scripts section in the Inspector. To attach a script:

  • drag the .rs file from the Assets panel onto the Scripts section ("Drop to add script"), or onto the entity's row in the Hierarchy, or
  • click the + in the Scripts header (Add Script) and pick it from the list.

The Inspector's Scripts section with spin.rs attached

An entity can carry several scripts. The same script can be attached to many entities; each one runs it separately.

When scripts run

While you are arranging your scene, scripts do nothing. They run:

  • when you press Play: the game starts in its own window and every script runs, or
  • when you turn on one script's play button in the Inspector. That runs just this script, live in the editor, so you can try it without starting the whole game. Press it again to stop.

Saving and compiling

Press Ctrl+S in the code editor. The script compiles in the background, so the editor never freezes, and the Console says compiled new_script (or recompiled the next time). If the script is running, the new version takes over right away.

When you open a project, the editor compiles its scripts the same way. A script that has not changed since last time is not compiled again. Scripts that do need a build finish a moment after the project opens, so a Play pressed in the first second or two may start before they are ready.

When something goes wrong

A compile error appears in the Console and in the Problems panel, with the line number in your file. Fix it and save again. A script that failed is not retried until you edit it, so one mistake does not fill the Console.

A panic (for example, indexing past the end of a list) does not crash the editor or the game. The Console names the script, the entity and the line:

panics_on_purpose.rs panicked on 2984v0: index out of bounds: the len is 0 but the index is 3 (at panics_on_purpose.rs:8:18)

Only that call stops. Everything else keeps running. Fix the file and save.

Logging

Write to the Console with Bevy's logging macros. They come with bevy::prelude::*.

fn update(ctx: &mut ScriptCtx) {
    if let Some(name) = ctx.name() {
        info!("{name} is at {:?}", ctx.get::<Transform>().map(|t| t.translation));
    }
}

info!, warn! and error! lines appear in the Console, labelled with the script's file name (city_build for city_build.rs). debug! and trace! stay out of it. While the game runs in its own window from Play, its output reaches the Console too, under Runtime.

What ctx gives you

Most of the time you work on your own entity, so those calls need no argument:

CallWhat it does
ctx.get::<T>()Read a component on this entity, such as Transform
ctx.get_mut::<T>()Change a component on this entity
ctx.has::<T>()Check whether this entity has a component
ctx.insert(...) / ctx.remove::<T>()Add or remove components on this entity
ctx.name()This entity's name, if it has one
ctx.entity()This entity's id
ctx.parent() / ctx.children()The entities above and below it in the Hierarchy
ctx.delta()Seconds since the last frame
ctx.elapsed()Seconds since the game started
ctx.get_on::<T>(e) / ctx.get_mut_on::<T>(e)A component on another entity
ctx.get_resource::<T>() / ctx.get_resource_mut::<T>()A resource: game-wide data such as input or time
ctx.world()The whole game world, for anything else

A component is one piece of data on an entity: its Transform (position, rotation, scale), its Name, its light, its physics body. Everything you see in the Inspector is a component.

ctx.world() hands you Bevy's full World. Spawning, searching and loading assets all go through it. Nothing is off limits: anything Bevy can do, a script can do.

Multiply movement by ctx.delta() so it runs at the same speed whatever the frame rate.

Recipes

Spin

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let dt = ctx.delta();
    if let Some(mut transform) = ctx.get_mut::<Transform>() {
        transform.rotate_y(1.5 * dt); // radians a second
    }
}

renzora::script!(update);

Bob up and down

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let t = ctx.elapsed();
    let dt = ctx.delta();
    if let Some(mut transform) = ctx.get_mut::<Transform>() {
        // Nudge up and down a little each frame, around wherever you placed it.
        transform.translation.y += (t * 2.0).cos() * dt;
    }
}

renzora::script!(update);

Move with the keyboard

Bevy's ButtonInput<KeyCode> says which keys are held.

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let speed = 5.0;
    let dt = ctx.delta();

    let Some(keys) = ctx.get_resource::<ButtonInput<KeyCode>>() else { return };
    let mut dir = Vec3::ZERO;
    if keys.pressed(KeyCode::KeyW) { dir.z -= 1.0; }
    if keys.pressed(KeyCode::KeyS) { dir.z += 1.0; }
    if keys.pressed(KeyCode::KeyA) { dir.x -= 1.0; }
    if keys.pressed(KeyCode::KeyD) { dir.x += 1.0; }

    if let Some(mut transform) = ctx.get_mut::<Transform>() {
        transform.translation += dir.normalize_or_zero() * speed * dt;
    }
}

renzora::script!(update);

For controls the player can rebind, and that work with a gamepad too, read the project's input actions instead. See Input.

use bevy::prelude::*;
use renzora::{ActionState, ScriptCtx};

fn update(ctx: &mut ScriptCtx) {
    let dt = ctx.delta();
    let Some(actions) = ctx.get_resource::<ActionState>() else { return };
    let stick = actions.axis_2d("move"); // WASD, arrows or the left stick
    let jump = actions.just_pressed("jump");

    if let Some(mut transform) = ctx.get_mut::<Transform>() {
        transform.translation += Vec3::new(stick.x, 0.0, -stick.y) * 5.0 * dt;
        if jump {
            info!("jump!");
        }
    }
}

renzora::script!(update);

Follow another entity

Find the target by its name in the Hierarchy, then move a little toward it each frame.

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let dt = ctx.delta();

    // Look for an entity named "Player".
    let world = ctx.world();
    let mut named = world.query::<(Entity, &Name)>();
    let Some(target) = named
        .iter(world)
        .find(|(_, name)| name.as_str() == "Player")
        .map(|(e, _)| e)
    else {
        return;
    };

    let Some(goal) = ctx.get_on::<Transform>(target).map(|t| t.translation) else { return };
    if let Some(mut me) = ctx.get_mut::<Transform>() {
        let to_goal = goal - me.translation;
        if to_goal.length() > 2.0 {
            me.translation += to_goal.normalize() * 3.0 * dt;
        }
        me.look_at(goal, Vec3::Y);
    }
}

renzora::script!(update);

Searching every entity by name each frame is fine for a handful of followers. Rename the target and the follower stops, so keep the name in step.

Talk to your children

ctx.children() lists the entities parented under this one, so a script on a lamp post can switch off the light beneath it:

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let night = (ctx.elapsed() / 10.0) as u32 % 2 == 1;
    for child in ctx.children() {
        if let Some(mut light) = ctx.get_mut_on::<PointLight>(child) {
            light.intensity = if night { 100_000.0 } else { 0.0 };
        }
    }
}

renzora::script!(update);

Spawn something

Spawning goes through ctx.world(). Give everything you spawn a Name. A running game removes any placed entity that has no name, because an unnamed entity would be invisible in the Hierarchy and never saved or cleaned up.

use bevy::prelude::*;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let pressed = ctx
        .get_resource::<ButtonInput<KeyCode>>()
        .is_some_and(|keys| keys.just_pressed(KeyCode::Space));
    if !pressed {
        return;
    }

    let at = ctx.get::<Transform>().map(|t| t.translation).unwrap_or_default();
    let world = ctx.world();
    let mesh = world.resource_mut::<Assets<Mesh>>().add(Cuboid::new(0.3, 0.3, 0.3));
    let material = world
        .resource_mut::<Assets<StandardMaterial>>()
        .add(Color::srgb(1.0, 0.6, 0.1));
    world.spawn((
        Name::new("Spawned Box"),
        Mesh3d(mesh),
        MeshMaterial3d(material),
        Transform::from_translation(at + Vec3::Y * 2.0),
    ));
}

renzora::script!(update);

Add a physics body and collider to what you spawn and it will fall and land. See Physics.

React to a collision

Any entity with a physics body keeps a list of what it is touching, PhysicsContacts. This script on a player picks up anything named "Coin" it bumps into:

use bevy::prelude::*;
use renzora::physics::PhysicsContacts;
use renzora::ScriptCtx;

fn update(ctx: &mut ScriptCtx) {
    let touching: Vec<Entity> = ctx
        .get::<PhysicsContacts>()
        .map(|contacts| contacts.entities().collect())
        .unwrap_or_default();

    for other in touching {
        let is_coin = ctx.get_on::<Name>(other).is_some_and(|n| n.as_str() == "Coin");
        if is_coin && ctx.world().try_despawn(other).is_ok() {
            info!("Picked up a coin");
        }
    }
}

renzora::script!(update);

Mark the coin's collider Is Sensor in the Inspector so the player passes through it instead of bumping off. Forces, velocity and ray casts are on the Physics page.

Lifecycle hooks

update runs every frame. For things that happen once, or only when something occurs, add a second function and name it in script!:

use bevy::prelude::*;
use renzora::{ScriptCtx, ScriptHook};

fn update(_ctx: &mut ScriptCtx) {}

fn hooks(ctx: &mut ScriptCtx, hook: &ScriptHook) {
    match hook {
        ScriptHook::Ready => {
            info!("{:?} is ready", ctx.name());
        }
        ScriptHook::SceneLoaded { path, error: None } => {
            info!("loaded {path}");
        }
        _ => {}
    }
}

renzora::script!(update, hooks = hooks);

Always keep the _ => {} line at the end: new hooks may be added later, and it keeps your script compiling when they are.

HookWhen it fires
ReadyOnce, on the first frame the script runs on this entity, before its first update
FixedUpdate { delta }On the fixed physics clock. The place for forces and velocities, so they do not depend on frame rate
SceneLoaded { path, error }A scene finished loading, or failed to. Only scripts that survive the load hear it, such as those in a global scene, which is how a loading screen works
Ui { name, .. }A button or other control in your game UI fired a callback. See Game UI
Draw { width, height }Time to repaint this entity's drawing canvas
AnimationEvent { name, .. }An animation passed a marker. See Animator
Event { name, args, .. }A game event sent by another script or by engine code
Rpc { name, args, from }A message from another player arrived. See Multiplayer
PlayerJoined { id } / PlayerLeft { id }A player connected or left (on the host or server only)

Good to know

  • Settings live in components, not in the script. A Rust script has no fields of its own in the Inspector. Read the values you want to tune from components the entity already has (its light, its body, its transform), which the Inspector edits.
  • One file per script. A script cannot be split across modules. If you outgrow that, write a plugin.
  • Memory while editing. Each recompile keeps the old version in memory (about 200 KB). Restarting the editor frees it.
  • Exporting for another operating system (a Linux build from Windows, say): pick the Lean single binary packaging. The other packagings ship scripts only for the system you are exporting from. See Exporting.
  • Build files go in <project>/.renzora/scripts/. You never need to open or commit them.

Next steps

  • Input: action maps, rebinding and gamepads.
  • Physics: bodies, colliders and moving things with forces.
  • Rust scripts reference: every detail, including drawing, grids and exports.
  • Stuck? Ask on the Discord.