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
MediumIn main.gd:
- Add
var coins_left = 0at the top, and set it to the size of the groupcoinsin_ready(). - In
_on_coin_collected(), take one away and printCoins left:and the number, in place ofGot 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!")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Signals and Collisions
6Project: Coin Collector
Coin Collector: WalkCoin Collector: CoinsPractice on your own: Godot playground