Menu
CoddyTech

Recap: Coin Collector

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 8 of 85.

Time to put the chapter together: a field that remembers, a string built with +, an if and a comparison. Remember that Input.GetKeyDown is true once per press, and that == asks whether two values are equal.

challenge icon

Challenge

Medium

Every press of C collects a coin, and 5 coins win.

  1. Above Update(), add the field int coins = 0;.
  2. In Update(), on Input.GetKeyDown(KeyCode.C), add 1 to coins and log "Coins: " + coins.
  3. Inside that if, when coins == 5, also log You win!.

Press Play and press C five times: the Console counts Coins: 1 to Coins: 5, then You win!. Then Check.

Try it yourself

using UnityEngine;

public class CoinCounter : MonoBehaviour
{

    void Update()
    {
        // Each press of C collects a coin.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground