What is the purpose of `setget`?

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

I don’t understand the purpose of setget. I’ve searched Godot Docs, but all I found was “Defines setter and getter functions for a variable.” I assumed this means it’s a way to avoid writing out the full setter/getter function code.

So I tried this:

var warriorName          setget setWarriorName, getWarriorName

But this gets me the error, Parser Error: setter function 'setWarriorName' not found in class.

So, I guess it doesn’t let you skip typing out setters and getters?

What is the purpose of setget?

:bust_in_silhouette: Reply From: kidscancode

The setget keyword lets you define setter and getter functions that will be called whenever a particular variable’s value is changed. For example, if you want a signal emitted every time the player’s health changes, you can put that code in a setter function for the health variable.

You’re getting an error because that line of code says “When warriorName changes, call the setWarriorName function”, but you haven’t defined that function.

The full explanation can be read here:

Thanks! This helps a lot!

LuminousNutria | 2019-01-24 00:30

Im here because the the official godot site didnt help. What is the point of a setter and a getter? The setter sets it when it changes? But doesnt that happen anyways? I mean thats even why the function triggers. And get returns it? But dont I have the value anyways? I dont understand how that helps

Snaper_XD | 2020-02-13 21:16

You can add additional functionality when variable changes e.g.

var my_var = 0 setget setVar

func setVar(new_var):
    my_var = new_var

now when you call

self.my_var = 1


myObj.my_var = 1

the setVar function will be called and onVarChange function will be run.
Same with getter.
This is not possible with regular setters and getters without setget

kregi | 2020-04-04 19:48

Yes, but the purpose of mutators and accessors is to make the member variables private and trigger the functions externally by:


not by:

myObj.my_var = 1

or locally by:


not by:

self.my_var = 1

Therefore, the setget keyword is unecessary boilerplate. If you understand OOP, then don’t bother with setget.

ArcaneCoder | 2021-03-20 20:21