Time for action – counting cannonballs
As with all data operations, the first step is to create a variable that stores the data you want to interact with. To count the number of cannonballs that the player fires, we'll need to use an integer variable with a script that increments the count by one every time the
FireCannon
function is called. Perform the following steps to count cannonballs:
Create a new C# script named
ScoreKeeper
, and attach it to yourCannon
prefab.Automatically add the script to all future instances of your
Cannon
prefab by clicking on Apply in the Inspector window after you attach the script.Open the
ScoreKeeper
script, declare anint
variable namednumCannonballsFired
, and initialize it to0
in theStart
function as shown in the following code:private int numCannonballsFired; void Start() { numcannonballsFired = 0; }
Next, we need a public function that will increment the integer value by one every time it's called.
Create a new function named
IncrementCount
and add...