Nodes as Components
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 42 of 65.
A Node can have child nodes. Godot builds game objects this way: a hero node gets one child node per ability, such as health or movement. Each child is a component: a small node that does one job.
# health.gd
class_name Health
extends Node
var hp := 10
func _ready() -> void:
print("Health ready")
# hero.gd
class_name Hero
extends Node
func _init() -> void:
var health := Health.new()
health.name = "Health"
add_child(health)
func _ready() -> void:
print("Hero ready, hp: ", $Health.hp)add_child() attaches a node as a child. Give each component a name: get_node("Health"), or its short form $Health, finds the child by that name. A node without a name, or whose name is taken by a sibling, gets an automatic one such as @Node@4.
A node's _ready() runs when it enters the scene tree, the tree of nodes the game is running. main.gd is in the tree, so adding the hero to it starts both _ready() methods, the children's first:
# main.gd
var hero := Hero.new()
add_child(hero) # Health ready, then Hero ready, hp: 10
print(hero.get_child_count()) # 1A parent reaches its components with get_children() (an array of the children, in the order they were added), get_child_count() and has_node("Health"). Nodes in the tree are freed together with the tree when the game ends, so a component that was added with add_child() needs no cleanup.
Challenge
EasyBuild a robot from component nodes.
PartextendsNode. Its constructor receives a part name and a power value: it stores the power and sets the node'snameto the part name. When a part enters the scene tree, its_ready()printsLaser attached.RobotextendsNode.add_part(part_name, power)adds a newPartas a child. If the robot already has a child with that name, it printsLaser is already attachedand creates nothing.total_power()returns the sum of the power of all its parts.
The supplied code adds the robot to the scene tree, reads how many commands follow (add Laser 5, power), and prints the number of parts at the end. For add Laser 5, add Wheels 2, power, add Laser 9, add Arm 3, power it prints:
Laser attached
Wheels attached
Total power: 7
Laser is already attached
Arm attached
Total power: 10
Parts: 3Your code goes in part.gd and robot.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 robot := Robot.new()
add_child(robot)
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
if parts[0] == "add":
robot.add_part(parts[1], int(parts[2]))
else:
print("Total power: ", robot.total_power())
print("Parts: ", robot.get_child_count())
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