+1 vote

I just found out that there is "setget" in GDScript. But what is the advantage of using it?
At the moment I write getter and setter functions (e.g. in my global script) like this (like in learned in school with Java):

var test = 0

func set_test(var new_test):
    test = new_test

func get_test():
    return test

And then I can call e.g. Global.set_test(1) and Global.get_test() from my other scripts.

But what is the advantage/difference of using:

var test = 0 setget set_test,get_test

func set_test(var new_test):
    test = new_test

func get_test():
    return test
in Engine by (142 points)

1 Answer

+3 votes
Best answer

They're equivalent. Getters and setters are syntactic sugar to simplify the api. With setget, accessing or modifying the property will automatically call the getter/setter. It's useful if you want something to happen when accessing the prop, such as emitting a signal, performing validation or forwarding to a sub-property. Without setget, you run the risk of bypassing the getter or setter logic since you can access the prop directly. But if you don't make mistakes, it's not really useful.

by (1,100 points)
selected by
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.
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 webmaster@godotengine.org with your username.