Menu
CoddyTech

Property Setters

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 11 of 65.

A property can run code every time it is assigned. Put a colon after the declaration and add an indented set(value): block, its setter:

# player.gd
var health: int = 100:
	set(value):
		health = clampi(value, 0, 100)

value is what is being assigned. Inside the setter, assigning health stores the value in the property; it does not run the setter again. This setter keeps health between 0 and 100, whatever the rest of the program assigns:

var p := Player.new()
p.health -= 30
print(p.health) # 70
p.health = 250
print(p.health) # 100
p.health -= 500
print(p.health) # 0

The setter runs on every assignment, inside the class too: health -= 10 in a method of Player and health = start_health in _init() both go through it. Only the starting value after = in the declaration is stored without calling it.

A setter can also refuse a value. If it does not assign the property, the old value stays:

var level: int = 1:
	set(value):
		if value > level:
			level = value

Leave the type off value: set(value: int): is an error. The property's own type already says what it holds.

challenge icon

Challenge

Easy

Give the health property of the class Player in player.gd a setter that:

  • keeps the stored health between 0 and max_health: a larger value is stored as max_health and a negative one as 0
  • prints Player is down! when the new health is 0 and the old health was above 0

The supplied code reads how many commands follow, then one per line: damage N (player.health -= N), heal N (player.health += N) or set N (player.health = N). After each command it prints the health. For damage 30, heal 50, damage 120 and heal 10 it prints:

Health: 70
Health: 100
Player is down!
Health: 0
Health: 10

Your code goes in player.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var player := Player.new()
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		var amount := int(parts[1])
		if parts[0] == "damage":
			player.health -= amount
		elif parts[0] == "heal":
			player.health += amount
		elif parts[0] == "set":
			player.health = amount
		print("Health: %d" % player.health)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler