All lessons
Lesson 09

Collect Coins and Items

Pick up coins and watch a counter climb. Introduces signals: one event, two different files reacting to it.

Loading the game engine. This takes a moment the first time.

Build style

HOW THE COIN SIGNAL TRAVELS

game_events.gd creates it: signal coin_collected(value: int) At startup, hud.gd and this file each call .connect() one time, with a function name inside: .connect(_on_coin_collected) After that, every time coin.gd calls .emit(value), Godot runs the function each file named inside its own .connect(). One emit, two functions run. To trace any signal: highlight its name, press Ctrl + Shift + F.

The scenes

UI node · 2D node · % unique name · .tscn instanced scene

coin_pickup.tscn
  • CoinPickup Node2D coin_pickup.gd
  • Player CharacterBody2D player.tscn
  • Coin1 Area2D coin.tscn
  • Coin2 Area2D coin.tscn
  • Coin3 Area2D coin.tscn
  • HUD CanvasLayer hud.tscn
  • Walls StaticBody2D
  • TopWall CollisionShape2D
  • BottomWall CollisionShape2D
  • LeftWall CollisionShape2D
  • RightWall CollisionShape2D
coin.tscn
  • Coin Area2D coin.gd
  • ColorRect
  • CollisionShape2D
hud.tscn
  • HUD CanvasLayer hud.gd
  • MarginContainer
  • ScoreLabel Label %
  • HomeButton Button %
player.tscn
  • Player CharacterBody2D player.gd
  • Sprite2D
  • CollisionShape2D
Build style
extends Node2D

## How many coins are in this level. Change this if you add coins!
@export var total_coins: int = 3

var collected_coins: int = 0

func _ready() -> void:
	# We call ".connect" on the signal "coin_collected", and we put the name
	# "_on_coin_collected" inside it. That is the function Godot will run,
	# written on line 35 below.
	# hud.gd connects to this same signal, but names its own function.
	GameEvents.coin_collected.connect(_on_coin_collected)

# The "_" in "_value" means we ignore it. hud.gd is the file that uses "value".
func _on_coin_collected(_value: int) -> void:
	collected_coins += 1
	# "print()" shows up in Godot's Output panel. The player never sees it.
	if collected_coins >= total_coins:
		print("All coins collected!")