Setters & Getters
In programming, setters and getters are functions used to control the access of variables. They are quite useful when creating classes.
For each member variable, a getter function will return the variable value.
The setter function will update or “set” a value to a member variable.
To create a setter/getter method, use the setget
keyword followed the name
of the setter and getter method.
var <variable name> = <assignment value> setget <setter name> , <getter name>
A Basic Getter/Setter Function:
extends Node
class_name Human
# Both a setter & getter method established
var uniqueName = "John" setget setFunction, getFunction
func setFunction(param1):
uniqueName = param1
func getFunction():
return uniqueName
You are also able to pick and choose whether a member variable will only use a setter
or getter method.
To create only a setter method for a variable:
extends Node
class_name Human
# Only setter method established
var uniqueName = "John" setget setFunction
func setFunction(param1):
uniqueName = param1
To use only a setter, start with adding a comma ,
followed by the name of the setter
method:
extends Node
class_name Human
# Only getter method established
var uniqueName = "John" setget , getFunction
func getFunction():
return uniqueName
When to use Setter & Getter Methods
Use a setter/getter method when you want to do the following:
-
When you need to know when a value has had its value changed
-
When you need to perform an action if a variable value has changed
-
When you want to protect a variable from having the value changed
Resources
Github Project:
Godot Tutorials Resources