Implementing a lives counter

This recipe teaches us how to use a Text (Script) component, along with a script, to create a counter. It is similar to the counter in the previous recipe; however, instead of keeping track of the score, here we are managing the number of lives that the player has.

How to do it...

  1. Like the first step in the previous recipe, we need to create a new UI text to display the number of lives. Right-click on the Hierarchy panel and then go to UI | Text. Finally, rename it to LivesCounter.
  2. We can also adjust the appearance, as we have done before with the ScoreCounter, so change the Font and the Font size. We can also set the Color of the text to white, and, finally, we place it in the scene through the Rect Tool, and so on.
  3. Ensure again that the Rich Text variable is checked in order to use styling tags.
  4. Next, let's create the script that manages the number of lives: click on Add Component | New Script in the Inspector, name it LivesCounterScript and then press Create and Add.
  5. Double-click on the script in order to edit it. As the previous recipe, we are going to use the Text class; therefore, we need to add the using UnityEngine.UI; statement at the beginning of the script.
  6. Unlike the previous recipe, we need three variables, two private and one public, so that we can set this last one in the Inspector. These three variables are as follows:
      private Text uiText;
      public intmaxLives;
      private int lives;
  7. In the Start() function, we can set the uiText and lives variables and call our update function that we will write later, so:
      void Start () {
        lives = maxLives;
        uiText = this.GetComponent<Text> ();
        updateLivesCounter();
      }
  8. Now we can write the addLife() function. Since we have set the maximum number of lives in the maxLives variable, we need to pay attention to not exceed that number. As a result, we need to add some more lines to perform this control. Furthermore, when we call this function, we don't know if it takes effect; thus, we need to return a value — in this case Boolean — to let us know if this operation succeeded or not. The function is as follows:
      public booladdLife(){
        if (lives <maxLives) {
          lives++;
          updateLivesCounter();
          return true;
        }
        return false;
      }
  9. Of course, there is also a function for removing lives; it is as follows:
      public boolloseLife(){
        lives--;
        if (lives > 0) {
          updateLivesCounter();
          return false;
        }
        lives = 0;
        updateLivesCounter();
        return true;
      }
  10. Finally, our update function:
      private void updateLivesCounter(){
        uiText.text = "<color=red>Lives</color>: " + lives;
      }
  11. Save the script, and our LivesCounter is ready. If we set to 5 the maxLives variable and press play, we should see the following:
    How to do it...

How it works...

As in the Implementing a score counter recipe, we have created a Text (Script) component and adjusted it as we desire, and again we have ensured that we have Rich Text checked.

In our script, we have three variables. The uiText stores the reference to the Text (Script) component. We store the maximum number of lives that the player can have in the maxLives variable and set its value in the Inspector. Finally, the lives contains the number of lives currently possessed by the player.

In the Start() function, we first set the number of lives with the maximum number allowed with this line, lives = maxLives;. Then, we assign the Text (Script) component attached in the same game object of this script to the uiText variable by calling the this.GetComponent<Text>() function. Finally, we call the updateLivesCounter() function in order to update the UI, also in the first iteration.

Furthermore, we have also written a addLife() function to add life to the player that returns a Boolean value: true if the life is added, otherwise the number of lives is equal to the maximum number of lives, which are allowed and the function returns false. In fact, at the beginning, there is an if statement that checks whether lives are less than maxLives. If so, we increase the lives by one, lives++;, then we call updateLivesCounter() function to update the interface, and, finally, we return true. Otherwise, we just return false.

Now, we have a function for loseLife(), and even this one returns back a Boolean value: true if the player has no more lives or false if the player has lives remaining. First, we decrease the number of lives by one, lives--;, and then we check whether lives are more than zero. If so, we call the updateLivesCounter() function to update the interface and, finally, we return false. Otherwise, we set lives = 0; since we don't want a negative number of lives, and, after updateLivesCounter(), we return true.

Finally, in the updateLivesCounter() function, there is just one line of the code. We assign to the text variable inside the Text (Script) component a string, with stylistic tags, along with the lives variable.

There's more...

We can extend the functionalities of our lives counter by following the next section that will explain how to change the maximum number of lives at runtime.

Changing the number of maxLives

Maybe there are some bonus pick-up items in our game that can temporarily increase the maximum number of lives. In this case, we will need a some other functions in our script; let's add them:

  public void increaseMaxLives(int value){
    maxLives += value;
  }

This function is very simple: the following line of code adds an amount equal to the value passed as parameter to the maxLives variable:

  public void decreaseMaxLives(int value){
    maxLives -= value;
    if (maxLives< 1)
      maxLives = 1;
    if (lives >maxLives)
      lives = maxLives;
  }

The descreaseMaxLives() function is a little bit more complex since we have to make more controls. First of all, we decrease the maxLives variable with the maxLives -= value; line. Then, we have two if statements: the first checks whether the maxLives is less than 1, since the player must have the possibility to have at least one life, and, if so, the maxLives variable is set to 1. The second checks to see that lives doesn't exceed maxLives, since the player can't have more lives that the maximum allowed, and, if so, set lives = maxLives.

Getting the number of lives

If we need to retrieve the value of the variable lives for any reason, such as to display this value somewhere else or allow the player to engage in a battle only if he has a certain number of lives, we need to add a get function, like the following one:

  public intgetLives(){
    return lives;
  }

See also

  • For more detail about the get function, please refer to Implementing a score counter recipe in the There's more... section.
  • Furthermore, if we want to replace the string lives on the counter with an icon, see the recipe Creating a modular coin counter, which teaches you how to add an icon for coins in the counter.
  • Instead, if we are looking for more information about Rich Text, the official documentation is the best place to get it: http://docs.unity3d.com/Manual/StyledText.html.
..................Content has been hidden....................

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