+2 votes

I want to write return functions

asked Dec 15, 2018 in Engine by JulioYagami (631 points)

2 Answers

+1 vote

Both setter and getter:

var my_var setget my_var_set, my_var_get

func my_var_set(new_value):
    my_var = new_value

func my_var_get():
    return my_var # Getter must return a value.

Only a setter

var my_var = 5 setget myvar_set

Only a getter

var my_var = 5 setget ,myvar_get


answered Dec 15, 2018 by hilfazer (2,110 points)
+12 votes

You use setgetwhen defining variables that are outside functions. The syntax is as follows.

var setter_and_getter setget setter, getter
var only_setter setget setter
var only_getter setget , getter

# Any initialization of a variable most be done before setget.
var setget_initialized = 0 setget setter, getter

The setter and getter are functions that you must define in the script. The simplest example of these two are as follows.

func setter(value):
     something = value

func getter():
     return something

The setter function is called whenever it's corresponding variable gets set.
And the getter is called when said variable is accessed in anyway.

 #assuming something is from a different script
 something = 0 # setter gets called.
 var other = something # getter gets called.

They won't be called however if the variable being manipulated is inside the same script it was defined.

 #assuming something is in the same script
 something = 0 # setter does not get called.
 self.something = 0 # doing this will make the setter get called.
answered Dec 15, 2018 by SIsilicon (3,779 points)

From what I can see, the setter is also not called if the property is modified in a script that extends the script that declared the variable.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.