A setter runs every time a variable is assigned. A getter runs every time it is read. In Godot 4 you write them right under the variable:
hp is now 70
hp is now 100
hp is now 0
set(value):receives the new value. Inside it,hp = ...stores the value directly, without calling the setter again.- The setter runs for every assignment, including
+=and assignments from the script's own functions. - The starting value,
100here, is stored without running the setter.
Getters and Computed Properties
A getter that returns a value worked out from other variables makes a computed property:
40.0
true
GDScript has no true read-only property. Assigning to hp_percent is allowed but has no effect on what it returns, because the getter never reads the stored value. Leave such a property unassigned, or add a setter that calls push_error().
Setter and Getter Functions
For longer logic, point the property at named functions with set = and get =:
0.0
250.0
This form is also what Godot 3's setget turned into: var speed setget set_speed, get_speed is now var speed: set = set_speed, get = get_speed.
Reacting to a Change
The most useful setter emits a signal, so the UI updates whenever the value changes and nothing else has to remember to tell it:
Label shows: 5
Label shows: 15
Setters on Exported Variables
An exported variable's setter runs when Godot loads the saved value, which can be before child nodes are ready. Guard node access with is_node_ready():
@export var color := Color.WHITE:
set(value):
color = value
if is_node_ready():
$Sprite2D.modulate = color
func _ready():
$Sprite2D.modulate = color
To see the change in the editor, not only in the running game, add @tool at the top of the script.
Common Mistakes
- A setter that never stores the value. If the setter only prints, the variable keeps its old value. Assign it inside the setter.
- Heavy work in a getter. A getter runs on every read, so a getter that loops over 1,000 nodes runs that loop each time.
Frequently Asked Questions
How do I write a setter in Godot 4?
Put set(value): in an indented block after the variable: var hp := 100: then set(value): and hp = clampi(value, 0, 100). Inside the setter, assigning to hp stores the value without calling the setter again.
What replaced setget in Godot 4?
Godot 3's var hp setget set_hp, get_hp became var hp: set = set_hp, get = get_hp, or an inline set(value): and get: block under the variable.
Is the setter called inside the same script?
Yes. In Godot 4 every assignment runs the setter, also from the class's own methods. The only exception is inside the setter and getter themselves. In Godot 3 you had to write self.hp = x to trigger it; that is no longer needed.
Is the setter called for the initial value?
No. var hp := 100: with a setter stores 100 without running the setter. For an @export variable, the value saved in the scene is applied through the setter when the node loads.