【问题标题】:How to check if node has property without instancing?如何在不实例化的情况下检查节点是否具有属性?
【发布时间】:2022-10-30 10:33:48
【问题描述】:

我正在尝试检查某个节点类型是否具有属性
实际上不需要创建它的实例

像这样:

print("z_index" in Position2D);

【问题讨论】:

    标签: godot gdscript


    【解决方案1】:

    ClassDB 中的课程

    如果我们谈论的是内置类(不是您创建的自定义类,而是 Godot 的一部分),您可以使用 ClassDB 获取属性:

    var properties := ClassDB.class_get_property_list("Position2D")
    

    Godot 脚本中的类

    如果类不在ClassDB中(就是自定义类的情况),但是你有脚本,可以使用脚本获取属性列表:

    var properties := preload("res://custom_class.gd").get_script_property_list()
    

    如果您没有脚本,也许您可​​以找到它。此代码使用隐藏的项目设置"_global_script_classes" 来查找给定您正在寻找的name_of_class 的类的脚本路径,并加载它:

    if ProjectSettings.has_setting("_global_script_classes"):
        for x in ProjectSettings.get_setting("_global_script_classes"):
            if x.class == name_of_class:
                return load(x.path)
    

    其他类

    但是,上述方法不适用于每种类型的脚本。在这些情况下,恐怕最好的方法是实例化它。您仍然可以从实例中获取属性并缓存它们(也许将它们放在字典中),这样您就不会在每次需要查询时都创建新实例:

    var properties := (CustomClass.new()).get_property_list()
    

    查询属性

    无论您如何获得属性列表,您都可以以相同的方式查询它们。例如,此代码查找名称为 "z_index" 的属性并获取其类型:

    var found := false
    var type := TYPE_NIL
    for property in properties:
        if property.name == "z_index":
            found = true
            type = property.type
            break
    
    prints(found, type)
    

    类型是Variant.Type 常量。

    【讨论】:

      【解决方案2】:

      在 Godot 4 中,您还可以通过以下方式进行检查:

      if "attribute_name" in thing:
        pass # do stuff here
      

      实际例子;在两个 Area2D 碰撞触发信号期间,检查是否设置了一个节点的属性item_type

      func _on_area_2d_area_entered(area):
        if "item_type" in area:
          print(area["item_type"])
      

      【讨论】:

        猜你喜欢
        • 2022-06-27
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 2011-01-31
        • 1970-01-01
        相关资源
        最近更新 更多