Scripting the cucumber count

Let's start with our cucumber count:

  1. In the Hierarchy panel, select HUD_Canvas | Cucumber_Count
  2. In the Inspector panel, click the Add Component button
  3. Select New Script and name the script CucumberManager
  4. Edit the script

With the script open, make the necessary modifications to match the script provided, as follows:

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CucumberManager : MonoBehaviour {

public int currentCucumberCount;
Text Cucumber_Count;
public GameObject[] cucumbers;


void Awake () {

Cucumber_Count = GetComponent<Text> ();
currentCucumberCount = 0;
}


void Update () {

cucumbers = GameObject.FindGameObjectsWithTag ("Cucumber");
Cucumber_Count.text = cucumbers.Length.ToString();
}
}

As you can see, we are using the UnityEngine.UI namespace. Inside the CucumberManager class, we declare three variables, establish an initial count of zero in the Awake() method, and then count the amount of cucumbers every frame in Update(), providing an on-screen update of the number of cucumbers left in the game. The ease with which we were able to program this was partially due to our assigning of the Cucumber tag to all of our cucumbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset