Menu
CoddyTech

Coin Collector: Coins Left

Part of the Signals and Collisions section of Coddy's Godot journey. Lesson 26 of 27.

Main should know how many coins are left. Keep the number in a variable at the top of main.gd. Count the group once at the start, then subtract one for each coin collected:

var coins_left = 0

func _ready():
	coins_left = get_tree().get_nodes_in_group("coins").size()

Why not count the group in _on_coin_collected? The coin sends collected just before it frees itself. It stays in its group until the end of the frame, so the count would include it.

A variable changes only when you change it.

challenge icon

Challenge

Medium

Make Main count the coins that are left.

  1. At the top of main.gd, add var coins_left = 0, and in _ready() set it to the size of the group coins.
  2. In _on_coin_collected(), take one away and print it in place of Got a coin!: print("Coins left: ", coins_left).

Press Play and take a coin: the Console shows Coins left: 5. Then Check.

Try it yourself

extends Node2D

func _ready():
	for coin in get_tree().get_nodes_in_group("coins"):
		coin.collected.connect(_on_coin_collected)

func _on_coin_collected():
	print("Got a coin!")

All lessons in Signals and Collisions

Practice on your own: Godot playground