【问题标题】:Avoid invoking setget function on starting up避免在启动时调用 setget 函数
【发布时间】:2022-10-06 06:01:51
【问题描述】:

我有一个像这样的简单脚本:

tool
extends Node2D

export(int) var example_value=0 setget set_example_value

func set_example_value(val):
    print(\"Setting example_value=\",val)
    
    #time/memory consuming code segment here
    
    example_value=val

我将example_value设置为3,然后退出游戏引擎

现在,当我再次启动 godot 时,set_example_value() 被调用来设置值,
有什么方法可以将example_value 设置为 3没有被调用的setter函数?

我为什么要这样做?

因为我有一个时间/内存消耗函数,当值改变时会生成精灵,
因此,当我启动 godot 时,我不想重新创建那些精灵,我只想将值更改为关闭 godot 之前的值

    标签: godot gdscript


    【解决方案1】:

    请先阅读我对Play animation without invoking setget? 的回答。


    不同之处在于我们将告诉 Godot 只存储其中一个。我们可以通过_get_property_list 做到这一点。因此,我们不会使用export。

    例如我们可以这样做:

    var example_value := 0
    
    func _get_property_list() -> Array:
        return [
            {
                name = "example_value",
                type = TYPE_INT,
                usage = PROPERTY_USAGE_EDITOR
            }
        ]
    

    并且编辑器会显示变量,因为它有PROPERTY_USAGE_EDITOR,但它不会被存储,因为它没有PROPERTY_USAGE_STORAGE。

    如果它没有被存储,那么在加载 Godot 时不会找到它,也不会设置它(注意它可能在你告诉 Godot 不存储它之前已经存储了......再次保存资源将修复它,或者使用外部编辑)。


    现在的问题是您根本没有保存价值。所以我们将有两个属性。一个只供编辑器使用,一个只用于存储。并且存储不会进行昂贵的过程。像这样:

    tool
    extends Node
    
    var example_value := 0 setget set_example_value
    func set_example_value(mod_value:int) -> void:
        print("HELLO")
        example_value = mod_value
    
    
    var example_value_storage:int setget set_example_value_storage, get_example_value_storage
    func get_example_value_storage() -> int:
        return example_value
    
    
    func set_example_value_storage(mod_value:int) -> void:
        example_value = mod_value
    
    
    func _get_property_list() -> Array:
        return [
            {
                name = "example_value",
                type = TYPE_INT,
                usage = PROPERTY_USAGE_EDITOR
            },
            {
                name = "example_value_storage",
                type = TYPE_INT,
                usage = PROPERTY_USAGE_STORAGE
            }
        ]
    

    【讨论】:

      猜你喜欢
      • 2011-10-17
      • 1970-01-01
      • 2012-03-30
      • 2011-09-18
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多