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
MediumEvery press of C collects a coin, and 5 coins win.
- Above
Update(), add the fieldint coins = 0;. - In
Update(), onInput.GetKeyDown(KeyCode.C), add 1 tocoinsand log"Coins: " + coins. - Inside that if, when
coins == 5, also logYou 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground