Properties
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 6 of 65.
The variables a class declares are its properties (also called member variables): the data every object carries. Declare them at the top of the class, each with a type and a starting value:
# player.gd
class_name Player
extends RefCounted
var player_name: String = "Hero"
var level: int = 1
var hp: float = 100.0
var inventory: Array[String] = []A property declared without a value starts at the default of its type: 0 for int, "" for String, false for bool and an empty array for Array[String].
Outside the class you read and change a property with a dot. Inside the class's methods you use its name:
var p := Player.new()
p.level += 1
p.inventory.append("sword")
print(p.level) # 2
print(p.inventory) # ["sword"]Every object gets its own copy of each property, arrays included: the [] creates a new empty array for each player, so another player's inventory stays empty.
The type is checked: p.level = "max" is an error reported before the program runs, because level holds an int.
Challenge
EasyComplete the class Player in player.gd. Declare these properties:
player_name, aStringthat starts as"Hero"level, anintthat starts at1hp, anintthat starts at100inventory, anArray[String]that starts empty
Then complete the method describe(). It returns NAME (level LEVEL, HP hp): ITEMS, where ITEMS is the inventory joined with ", ", or no items when the inventory is empty.
The supplied code reads a name for one player, then how many commands follow, then the commands: hit AMOUNT, item NAME or level. It changes the player's properties directly and finally prints describe() for that player and for a second player it never changed. For Ada and the commands hit 30, item sword, level and item shield it prints:
Ada (level 2, 70 hp): sword, shield
Hero (level 1, 100 hp): no itemsYour 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 hero := Player.new()
hero.player_name = OS.read_string_from_stdin()
var guest := Player.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
match parts[0]:
"hit":
hero.hp -= int(parts[1])
"item":
hero.inventory.append(parts[1])
"level":
hero.level += 1
print(hero.describe())
print(guest.describe())
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