_set and _get have no effect

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By thornySoap

What do I do wrong or misunderstand here?


extends Node

var my_var: int

func _set(property: StringName, value: Variant) -> bool:
    print(property, " ", value)
    if property == "my_var" and value is int:
        my_var = 5
    return true


extends Node

func _ready() -> void:
    $Node1.my_var = 7



output I would like to have:

my_var 7

You didn’t actually call _set, which is defined as a (private) function of whatever the script is attached to (Node1).

Perhaps you meant to write a setter and getter? The syntax is as described in the doc.

var my_var: int:
        return my_var
        my_var = 5 # ignoring 'value' here, seems you want to '5'?

spaceyjase | 2023-05-26 14:59

Of course everything works fine, if I directly call _set, but I thought _set is called automatically to “customize the behavior of set” (docs).

thornySoap | 2023-05-26 15:17

Ah, I see. Not quite… you still need to call set for the property.

func _ready() -> void:
	$Node1.set("my_var", 7)
	print($Node1.my_var) # prints 5


var _my_var: int

func _set(property, _value):
	if property == "my_var":
		_my_var = 5

func _get(property):
	if property == "my_var":
		return _my_var

The previous code ($Node1.my_var) pokes directly at the index member and won’t run the _set override. I believe a combination of tool scripts and _get_property_list might allow some sensible syntax (e.g. node.my_var) but I’m not sure.

spaceyjase | 2023-05-26 16:00

Thank you so much. Adding this allowed me to do node.my_var:

func _get_property_list() -> Array[Dictionary]:
    return [{"name": "my_var", "type": TYPE_INT}]

It seems like I have confused some things in my actual project (not this test thing) where I already used _get_property_list() for something. But because I wanted to use _set() for another real attribute which of course doesn’t work because you then have to define a setter, I thought those fake attributes also wouldn’t work, even though they actually did.

thornySoap | 2023-05-26 17:55