Implementing a score counter

In this recipe, we are going to create a score counter that displays the score as a number on the screen. To achieve this, we will use the Text (Script) component and create a script to handle it. Different functions will be available from this script, that will be called from other scripts to increase the score.

How to do it...

  1. First of all, we need to create new UI text to display our score. Thus, right-click on the Hierarchy panel and then UI | Text. Finally, rename it to ScoreCounter.

    Tip

    To rename an object, right-click on it and select Rename. Otherwise, we can change its name in the Inspector window.

  2. Next, we can change the Font and the Font Size in the Inspector as we wish, to better suit our needs.
  3. Furthermore, we should also adjust the Color. In this example, we will set it to white in order to be easily visible within the scene.
  4. Now, we need to drag the ScoreCounter with the Rect Tool (the hotkey for this tool is T, and we have seen it in the previous chapter) to where we want to place it.
  5. We can write in the Text variable the word Score. In fact, this helps us to visualize what the counter will look like, even though this value will be replaced by the script, which we are going to write in the next steps.
  6. Ensure that the Rich Text variable is checked. This allows us to use different colors inside the counter.
  7. In this step, we need to create a script that manages the score: click on Add Component | New Script in the Inspector and name it ScoreCounterScript, and then press Create and Add. In doing this, ensure that the language selected is C Sharp.
  8. Double-click on the script in order to edit it. Since we are going to use the Text class, we need to add the using UnityEngine.UI; statement at the beginning of the script.
  9. Before we add the functions in our script, we need two private variables. Hence, we can write:
      private Text uiText;
      private long score = 0;
  10. In the Start() function, we can store the ScoreCounter in the uiText variable so that we can refer to it later in the script. In addition, we need also to update our score, so let's call a function that we will write later. Thus, the Start() function is as follows:
      void Start () {
        uiText = this.GetComponent<Text> ();
        updateScoreCounter ();
      }
  11. Next, we need a function to add points to our score counter that can be called from other scripts. We pass it an int parameter, which is the amount of points the player earned. So we can write the following:
      public void addPoints(int points){
        score += points;
        updateScoreCounter ();
      }
  12. Finally, since we have called the updateScoreCounter() function twice, it's time to write it down:
      private void updateScoreCounter(){
        uiText.text = "<color=blue>Score</color>: " + score;
      }
  13. We can save the script and the work is done. We should see something like the following:
    How to do it...

How it works...

In the script, there are two variables, uiText and score, which we've set to private because other components do not need to access it. The former stores the reference to the Text (Script) component in order to get it later in the script; the latter is the score of the player. This last one is a long variable that allows us to store big numbers since in some games, score points are very huge numbers.

The Start() function in Unity is special since it is called only once when the script is enabled for the first time. In this function, we assign the Text (Script) component attached in the same game object of this script to uiText variable by calling the this.GetComponent<Text>() function. Then, we call the updateScoreCounter() function in order to update the UIs as well during the first iteration.

Moreover, we added the addPoints(int points) function. It takes an int as a parameter named points. Then, the function adds this value to the score variable through score += points;. Finally, we call updateScoreCounter() to update the interface. The += operator will take the value that score currently is and increase it by whatever is in our points value.

Finally, the updateScoreCounter() function changes the text variable on the Text (Script) component stored in the uiText variable. In fact, the new value assigned is a string. In the first part of this function, there is <color=blue>Score</color>: that encloses the word Score into styling tags to change its color to blue. Of course, we can also change blue to another color, if we prefer. Finally, we added the score. Don't worry that the score variable is long because in this case, Unity converts the number in to a string automatically.

There's more...

We have seen how to implement a score counter. However, according to the design of our game, we may want to add new features, such as removing score points or get the score variable to use it in some other script.

Adding a remove points function

In some games, it is possible to lose points, but we should be careful not to have a negative score.

Thus, we can deal with this issue by adding a new function to our script:

  public void removePoints(int points){
    score -= points;
    if (score < 0)
      score = 0;
    updateScoreCounter ();
  }

The first line score -= points; subtracts the amount of points, passed as parameter to the function, to our score.

Then, with an if statement, we verify whether our score is negative: if so, we set it to zero since we don't want negative score.

Finally, we update the score counter by calling the updateScoreCounter() function.

Using boldface in the rich text

The rich text of Unity allows us not only to change the color to a specific portion of text, but also to change the style. In order to give more importance to the word Score, we can replace this line of code inside the updateScoreCounter() function:

uiText.text = "<color=blue>Score</color>: " + score;

with this one:

uiText.text = "<b><color=blue>Score</color>:</b> " + score;

The text inside the <b> tag is now shown in boldface. Refer to the See also section for more details.

Getting the score

It could also be helpful to retrieve the score. For example, this is useful when we not only display it on the screen but also save the score in a scoreboard. Since we have set the score variable as private, we cannot access it directly. It's good practice not to change the variable into a public one but to add a new get function instead. The following is how we can do that:

  public long getScore(){
    return score;
  }

We simply return the score value and the job is done.

See also

  • If we want to explore the concept of resolution scaling, we can refer to the following recipe Resizing the UI according to the screen size and resolution.
  • Furthermore, if we want to replace the string Score on the counter with an icon, see Creating a modular coin counter recipe that teaches us also how to add an icon for coins in the counter.
  • Finally, if we are looking for more information about rich text, refer to the official documentation available at 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.135.206.254