Another Node's Signal
Part of the Signals and Collisions section of Coddy's Godot journey. Lesson 9 of 27.
A script can also listen to another node's signal. Get the node with $, then connect its signal:
$Switch.body_entered.connect(_on_switch_body_entered)This reads: when Switch sends body_entered, call _on_switch_body_entered. The function is in this script, so it can use this script's nodes, like $Light.
Games are often wired this way. One main script connects the switch, the light and the door, and each of those stays simple. Godot names such functions _on_, then the node, then the signal.
Challenge
EasyMake the switch turn the light on.
- In Main's
_ready(), start a line with$Switch.body_entered. - Connect it to
_on_switch_body_entered.
Press Play and step on the green switch: the light comes on. Then Check.
Try it yourself
extends Node2D
func _ready():
pass
func _on_switch_body_entered(body):
$Light.visible = true
All lessons in Signals and Collisions
2Signals
Areas Meet AreasYour Own SignalSignals With ValuesAnother Node's SignalListen to Your SignalPractice on your own: Godot playground