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) # 0The 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 = valueLeave the type off value: set(value: int): is an error. The property's own type already says what it holds.
Challenge
EasyGive the health property of the class Player in player.gd a setter that:
- keeps the stored health between
0andmax_health: a larger value is stored asmax_healthand a negative one as0 - prints
Player is down!when the new health is0and the old health was above0
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: 10Your 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler