Properties: Setters & Getters

Usage: health -= 10 calls the setter; print(health) calls the getter.

14.1 Syntax (Godot 4)

Usage: health -= 10 calls the setter; print(health) calls the getter.

signal health_changed(new_value: int)

var max_health := 100

var health: int = 100:
	set(value):
		health = clampi(value, 0, max_health)   # assigning to 'health' inside its own setter sets the backing field
		health_changed.emit(health)
	get:
		return health

var is_dead: bool:
	get:
		return health <= 0                      # computed property (no storage needed)

14.2 Separate functions

var speed: float = 100.0: set = set_speed, get = get_speed

func set_speed(value: float) -> void:
	speed = maxf(value, 0.0)

func get_speed() -> float:
	return speed

14.3 Setters with exported properties and @onready nodes

Setters run when the scene is loaded, possibly before _ready() — child nodes may not exist yet:

@export var color := Color.WHITE:
	set(value):
		color = value
		if is_node_ready():          # 4.1+: true after _ready has run
			$Sprite2D.modulate = color

func _ready() -> void:
	$Sprite2D.modulate = color

14.4 Rules

Inside the setter/getter, accessing the property directly uses the backing value (no infinite recursion).

From the same class, self.health = x and health = x both call the setter in Godot 4.

Setters do not run for the initial value written in the declaration.

Godot 3 note: var health = 100 setget set_health, get_health. In 3.x, setters were only called when accessed via self. from inside the class.