Adding Custom Properties With Godot Rust

Jun 21, 2020

I ran into a bit of trouble getting a custom property defined in a godot-rust project to show up in the Godot editor. It finally turned out that my difficulties were unrelated to Godot or godot-rust and actually a library misconfiguration error (I renamed my library’s name in Cargo.toml and forgot to fix the .gdnlib) but in the process I discovered that godot-rust’s documentation is rather lacking when it comes to the actual glue layer that ties Godot and the rust bindings together. So, here’s how you add a basic property:

  1. Tag the variable with a property macro:
    #[property(path = "camera/speed", default = 5.0)]
    translation_speed: f32

The path of the property will dictate how it appears in the inspector. If you specify a path of base, the property will appear as-is under Script Variables. If you specify a different path, the variable will appear under a group with that name. Properties with a common path will appear under the same group.

  1. The tagged property will show up in the Inspector for the scene object to which your script is attached.

Here’s what the code looks like:

use gdnative::*;

#[derive(NativeClass)]
#[inherit(ClippedCamera)]
#[user_data(user_data::MutexData<CameraController>)]
pub struct CameraController {
    #[property(path = "camera/speed", default = 5.0)]
    translation_speed: f32
}

#[methods]
impl CameraController {
    fn _init(_owner: ClippedCamera) -> Self {
        CameraController {
            translation_speed: 5.0,
        }
    }

    #[export]
    fn _ready(&self, _owner: ClippedCamera) {
         godot_print!("Translation speed is {}", self.translation_speed);
    }
}

And here’s what the root scene object looks like:

[gd_scene load_steps=4 format=2]

[ext_resource path="res://MainCamera.tscn" type="PackedScene" id=1]

[node name="Root" type="Spatial"]

[node name="MainCamera" parent="." instance=ExtResource( 1 )]
camera/move_speed = 6.0