Updating the inventory and HUD with cherry count

We now have a system in place for adding cherries to the Cucumber Man's inventory based on his collision with cherry trees. Next, we need to update the appropriate UI text component with the current inventory amount. We will take care of this important task in this section.

Here are the steps to create that script:

  1. In the Hierarchy panel, select the HUD_Canvas | Cherries_Count UI text component
  2. In the Inspector panel, scroll to the bottom and click the Add Component button
  3. Select New Script
  4. Name the script CherryManager
  5. Click the Create and Add button
  6. In the Project panel, click Favorites | All Scripts
  7. Drag the CherryManager script to the Assets | Custom Scripts folder
  8. Double-click the CherryManager script to open it in an editor
  9. Edit the script so that it matches the code provided here

An explanation of this code is provided immediately following the code block:

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

public class CherryManager : MonoBehaviour {

Text Cherries_Count;

void Awake () {

Cherries_Count = GetComponent<Text> ();

}


void Update () {

Cherries_Count.text = CucumberManManager.currentCherryCount.ToString ();

}
}

The first four lines of code import the appropriate namespaces.

The next line of code is the class declaration: public class CherryManager : MonoBehaviour {.

Next is the single class variable, a text object named Cherries_Count.

The first method in the class is the Awake() method. We use this method to create a reference to the Cherries_Count UI text component.

The last section of our CherryManager class is the Update() method. That method has a single statement used to convert the currentCherryCount from an int to a string and update the HUD.

You can play-test the game to validate the functionality. Simply navigate the Cucumber Man to a cherry tree and watch the inventory of cherries increase. It is important for us to have a method of collecting cherries because the player can press the E key on the keyboard to throw a cherry. We will program that functionality in the next section.

Now is a great time to save your scene and project. 
..................Content has been hidden....................

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