+6 votes

I want to write return functions

in Engine by (695 points)

2 Answers

+12 votes

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


by (2,302 points)
+33 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.
by (3,936 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.

this came up while searching so for anyone that encounters this, you have to change the property using the self keyword, e.g. self.something = 0, to trigger the setter from the parent.

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.