Signals With Values
Part of the Signals and Collisions section of Coddy's Godot journey. Lesson 8 of 27.
A signal can carry values, the way body_entered carries the body. List them in brackets when you declare it:
signal collected(points)Give the values to emit(), in the same order:
collected.emit(points)Every function connected to collected gets the value. Here the script on Main adds the points to the score and prints it:
func _on_gem_collected(points):
score += points
print("Score: ", score)Both gems run the same script. The small gem's points is 10 and the big gem's is 25, set on each node in the scene. So send points, not a number you type in.
Challenge
EasyMake each gem tell main.gd how many points it is worth.
- Declare
signal collected(points)at the top ofgem.gd. - At the end of
_on_body_entered, send it with the gem'spoints.
Press Play and walk over both gems: the Console shows Score: 10, then Score: 35. Then Check.
Try it yourself
extends Area2D
@export var points = 10
func _ready():
body_entered.connect(_on_body_entered)
func _on_body_entered(body):
if not visible:
return
visible = false
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