【GDExtension】自定义编辑器警告

我们都知道在官方原版给的一些组件里面,会有黄色三角提示“缺少XXX子节点”云云。GDExtension作为godot引擎的拓展模块,源代码部分对于godot编辑器是封闭的,这也符合软件设计的开闭原则。然而,当我们自定义的某个类需要依赖某个子节点时,我们缺乏有效的手段提示用户。

在之前已经有同学探索了如何在GDScript中自定义警告,根据这位同学的思路我将该方法拓展到了GDExtension中并进行了验证。代码实现如下:

  1. gdexample.h
// 必要的声明部分略去,自行查看GDExtension官方文档及其余相关教程文章
class GDExample : public Node {
// 略
private:
	void _check_children();
public:
	void _ready() override;
	PackedStringArray _get_configuration_warnings() const override;
// 略
}
  1. gdexample.cpp
// 略
#include <godot_cpp/classes/engine.hpp>
// 略
void GDExample::_bind_methods() {
	// 略
	// 注册_check_children方法
	ClassDB::bind_method(D_METHOD("_check_children"), &GDExample::_check_children);
}
// 私有方法,在子节点变化时候执行
void GDExample::_check_children(){
	if (Engine::get_singleton()->is_editor_hint()){
		// 继承自父类Node的方法,完整签名为:
		// void update_configuration_warnings()
		update_configuration_warnings();
	}
}
void GDExample::_ready() {
	if (Engine::get_singleton()->is_editor_hint())
	{
		// 绑定child_order_changed信号与_check_children方法
		connect("child_order_changed", Callable(this, "_check_children"));
		_check_children();
	}
}
// 覆写父类Node方法,完整签名为:
// virtual PackedStringArray _get_configuration_warnings() const;
PackedStringArray GDExample::_get_configuration_warnings() const {
	// 用于返回的字符串列表
    PackedStringArray warningStrings;
    // 这里仅作示例,检测到子节点数为0时警告用户
    if (this->get_child_count() == 0) {
    	// 必须使用宽字节字符,因为这是Windows系统默认的中文字符编码
        warningStrings.push_back(L"没有子节点");
    }
    return warningStrings;
}
// 略

编译运行过后,在项目中验证:
编译器警告
添加子节点之后黄色三角就消失了:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值