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
MediumMake Main count the coins that are left.
- At the top of
main.gd, addvar coins_left = 0, and in_ready()set it to the size of the groupcoins. - In
_on_coin_collected(), take one away and print it in place ofGot 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
6Project: Coin Collector
Coin Collector: WalkCoin Collector: CoinsPractice on your own: Godot playground