Creating a modular coin counter

This recipe teaches us how to use a Text (Script) and Image (Script) components along with a script to create a counter with an icon. It is similar to the counters in the two previous recipes, but, instead, to keep track of the score or lives, here we manage the number of coins possessed by the player. In contrast to the first counter that doesn't have an upper bound, or like the second counter that has a maximum for lives, here, when the player has reached a certain number of coins, something will happen. For example, a life will be added and the counter starts from zero, creating modularity.

How to do it...

  1. As for the first step of the previous recipe, we need to create a new UI text to show the number of lives. Hence, right-click on the Hierarchy panel and then UI | Text. Finally, rename it to Modular Coin Counter.
  2. Let's adjust the settings to suit our needs, such as Font, Font Size, and Color, and also write in the Text variable 0 (zero).
  3. In order to add an icon to our counter, we need to create an image inside the Modular Coin Counter, so right-click on it and select UI | Image, and then rename it to Modular Coin Counter Icon.
  4. The next step is to create the icon, so let's open a graphic program and create our icon:
    How to do it...

    Tip

    If we are using Photoshop, you can easy create this by using the ellipse tool: ensure that the main color is on yellow, and, then, while keeping Shift pressed, click on the upper left corner and drag to the lower right corner. Finally, select the Text tool and type a $, press Ctr+T, then scale, and place it at the center of the circle. Now we have a simple icon for coins.

    If you don't have a graphic program or you don't want to open a graphic program, you can use the image provided along with the code of this book.

  5. Right-click on the Project panel and select Import new asset; select the icon that we have just created and import it.
  6. If our project is set in 2D, we can skip this step. Otherwise, select the asset just imported in the Project panel and, in the Inspector, change Texture Type into Sprite (2D and UI). Finally, click on Apply.
  7. We can now add the icon to the Modular Coin Counter Icon in the Source Image variable and place it near the Modular Coin Counter. We should see something like the following:
    How to do it...
  8. It's time to implement the logic in the script. To begin, let's add it to the Modular Coin Counter, select Add Component | New Script, and then name it ModularCoinCounterScript. Finally, press Apply.
  9. Double-click on the script to edit it. We are going to use some UI classes, so we need to add the using UnityEngine.UI; statement at the beginning of the script.
  10. Before we can add functions, we need three variables, two private and one public, so we can set this last one in the Inspector. Thus, we can write:
      private Text uiText;
      public intmaxCoins = 100;
      private int coins = 0;
  11. In the Start() function, we set the uiText variable and then call our update function. The following is the Start() function:
      void Start () {
        uiText = this.GetComponent<Text> ();
        updateCoinCounter ();
      }
  12. Now, we allow other scripts to add coins through this function:
      public void addCoins(int value){
        coins += value;
        while (coins >= maxCoins)
          ApplyModularity ();
        updateCoinCounter ();
      }
  13. In the previous function, we called the ApplyModularity() function; let's write it down:
      private void ApplyModularity(){
        coins -= maxCoins;
        GameObject.Find ("LivesCounter").GetComponent<LivesCounterScript> ().addLife ();
      }
  14. Finally, as usual, our update function:
      private void updateCoinCounter(){
        uiText.text = coins.ToString();
      }
  15. As final step, save our work and the job is done.
    How to do it...

How it works...

In the script, we have created three variables. The first one is uiText and, as usual, it stores the reference to the Text (Script) component. The maxCoins variable is the number of coins after which the modularity is applied, and we can set its value in the Inspector, but as default in our script, it has 100 as value. Finally, the coins variable contains the number of coins currently possessed by the player and its default value is 0 (zero).

In the Start() function, we assigned the Text (Script) component attached in the same game object of this script to the uiText variable. We did this by calling the this.GetComponent<Text>() function. Then, we called the updateCoinCounter () function in order to update the UI also during the first iteration.

Furthermore, we have written a function to addCoins(int value) to the player that takes as an int parameter and it is the number of coins that will be added to the player. In fact, at the beginning, we added value to the coins variable by coins += value;. Then, there is a while loop: until the number of coins are more than the maximum allowed, we call the ApplyModularity() function. Since we don't know how many coins have been added with the value parameter, we have to apply the modularity as many times the number of maxCoins are into the coins variable. At last, of course, we call our updateCoinCounter () function in order to update the UI.

To better understand how the modularity works, let's consider the example of our ApplyModularity() function. First of all, this function is private, so only other functions within the same script can call it. Furthermore, it is called only when the number of coins are more than maxCoins, at most equal. So we can subtract the value of maxCoins from the coins variable, without obtaining a negative number of coins, and we do this in the first line of code. Then we can choose the reward for the player since he has reached the maxCoins number. In this example, if we have done this in Implementing a lives counter recipe, we can add a life to the player. So, let's find the lives counter through GameObject.Find ("LivesCounter") and then the script with GetComponent<LivesCounterScript> (). Finally, we can call the addLife () function.

At the end, we have updateCoinCounter(), in which we put the value of coins, converted in string through the ToString() function, into the Text variable contained into Text (Script) component in the Modular Coin Counter.

There's more...

Some improvements of the modular coin counter can be found in the following sections.

Removing coins

If in our game there is the possibility of losing coins, we can easily implement this feature by adding another function to our script:

  public void removeCoins(int value){
    coins -= value;
    if (coins < 0)
      coins = 0;
    updateCoinCounter ();
  }

The first line subtracted the value to the coins variable; then the if statement checks whether we have a negative coin number and, if so, set the coins variable to zero. Finally, we called our update function.

Adding score if the number of lives has reached the maximum

It may happen that the player has reached the maximum amount of lives that he is able to have, and if he reaches 100 coins, it would be unkind not give him a reward. In this case, we can reward him in another way. If we also did the score counter, we can give him some score points so that he doesn't lose the coins gained. Therefore, we need to change the ApplyModularity() function in the following way:

  private void ApplyModularity(){
    coins -= maxCoins;
    if (!GameObject.Find ("LivesCounter").GetComponent<LivesCounterScript> ().addLife ())
      GameObject.Find ("ScoreCounter").GetComponent<ScoreCounterScript> ().addPoints (230);
  }

Since the addLife() function returns true if a life is added or false if it is not, we can put it inside an if statement with a negation. Therefore, if the life is not added, the next line of code is executed. In fact, this adds 230 score points to the player, in the same way we have added a life, but instead of the LivesCounter, we search for ScoreCounter.

Getting the number of coins

If we need to retrieve the value of the coins variable for any reason, such as displaying them in a virtual shop, we will need to add a get function like the following one:

  public intgetCoins(){
    return coins;
  }

See also

  • We can refer to the two previous recipes about how to implement a lives counter or a score counter.
  • In addition, for more detail about the get function, please refer to the Implementing a score counter recipe, in the There's more... section.
..................Content has been hidden....................

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