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

In main.gd:

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

The first coin prints Coins left: 5.

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!")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Signals and Collisions

Practice on your own: Godot playground