+2 votes

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?

in Engine by (56 points)
edited by

1 Answer

+8 votes
Best answer

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:
https://docs.godotengine.org/en/latest/getting_started/scripting/gdscript/gdscript_basics.html#setters-getters

by (22,067 points)
selected by

Thanks! This helps a lot!

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

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

var my_var = 0 setget setVar

func setVar(new_var):
    my_var = new_var
    onVarChange()

now when you call

self.my_var = 1

or

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

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

myObj.set_var(1)

not by:

myObj.my_var = 1

or locally by:

set_var(1)

not by:

self.my_var = 1

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

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.