You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在基于gdext的Godot 4 Rust扩展中添加Inspector字段?

在gdext中为Godot 4 Rust扩展添加Inspector可编辑属性

核心实现方式

在gdext里,有两种方式能让属性在Inspector中展示并支持编辑,按需选择即可:

1. 直接注解结构体公共字段(简单场景首选)

给结构体的公共字段加上#[var]注解,就能自动在Inspector中显示,gdext会帮你生成对应的getter和setter,不用手动写额外代码。

示例代码:

use godot::prelude::*;

#[derive(GodotClass)]
#[class(base=Node)]
struct MyCustomNode {
    // 基础可编辑字段,默认在Inspector显示
    #[var]
    pub my_string: String,

    // 带数值范围限制的字段,Inspector会显示滑块
    #[var(hint = Range(min = 0.0, max = 100.0, step = 1.0))]
    pub my_number: f32,

    // 仅允许GDScript访问,不在Inspector显示
    #[var(hidden)]
    pub internal_value: i32,
}

#[godot_api]
impl MyCustomNode {}

#[godot_api]
impl NodeVirtual for MyCustomNode {
    fn init(base: Base<Node>) -> Self {
        Self {
            my_string: "Hello Inspector!".to_string(),
            my_number: 50.0,
            internal_value: 0,
        }
    }
}

2. 手动实现setter/getter方法(复杂逻辑场景)

如果属性读写需要额外逻辑(比如值校验、变更触发事件),可以用私有字段配合#[var]注解的getter和setter方法,把它暴露成Inspector可编辑属性。

示例代码:

use godot::prelude::*;

#[derive(GodotClass)]
#[class(base=Node)]
struct MyCustomNode {
    private_value: f32,
}

#[godot_api]
impl MyCustomNode {
    // Getter方法,用#[var]标记为属性的读取入口
    #[var]
    fn get_custom_value(&self) -> f32 {
        self.private_value
    }

    // Setter方法,命名要对应getter(set_前缀+属性名),同样加#[var]
    #[var]
    fn set_custom_value(&mut self, new_value: f32) {
        // 自定义逻辑:限制值在0-100之间
        self.private_value = new_value.clamp(0.0, 100.0);
        godot_print!("Custom value updated to {}", self.private_value);
    }
}

#[godot_api]
impl NodeVirtual for MyCustomNode {
    fn init(base: Base<Node>) -> Self {
        Self {
            private_value: 50.0,
        }
    }
}

关键注意事项

  • 直接注解字段时,字段必须是**公共(pub)**的;私有字段只能用setter/getter方式暴露。
  • #[var]支持多种hint参数,比如枚举选择、文件路径选择等,用来控制Inspector的显示和编辑规则。
  • 无论用哪种方式,结构体都必须先通过#[derive(GodotClass)]和#[class(base=Node)]标记为Godot可识别的类。

内容的提问来源于stack exchange,提问作者Mutant Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:04:57