Creating a health bar with armor

In this recipe, we are going to create a health bar, similar to the one in Implementing a linear health bar recipe, but there is an armor that protects the player. In fact, if the player is attacked, he or she will first lose the armor, then the health. To achieve this, we will use multiple Image (Script) components, both for the health bar and for the pieces of armor, and develop a script to manage the entire logic.

How to do it...

  1. To begin, let's create an image, so right-click on the Hierarchy panel and then UI | Image, and rename it HealthBar with Armor.
  2. Let's change Fill Method into Horizontal and Fill Origin into Left. Of course, we need to add the Healthbar that we have just created to Source Image. Finally, we can place the Healthbar with Armor everywhere we want, always using the Rect Tool.
  3. In order to keep its original proportion, you can click on the Set Native Size button in the Inspector.
  4. Next, right-click on Healthbar with Armor and add a new image by selecting UI | Image, and again rename the object just created as Armor1.
  5. Take an icon image to represent the pieces of the armor, or create on our own, and import it in our project. If our project is not set to 2D, remember to set the Texture Type of the icon to Sprite (2D and UI), and then click on Apply.
  6. Let's duplicate Armor1 with Ctrl+D as many times as lives the player will have. Rename them consecutively, such as Armor1, Armor2, Armor3, and so on.
  7. Distribute them in the Scene View while also keeping their order. For instance, Armor2 must be after Armor1 and before Armor3. This order is important because the script that we are going to write uses this order.
  8. Now, in the Healthbar with Armor, click on Add Component | New Script and name it HealthbarWithArmorScript, and then press Create and Add.
  9. Double-click on the script to edit it. Since we are going to use the Image class, we need to add the using UnityEngine.UI; statement at the beginning of the script.
  10. Before to add any functions, we need five variables, three private and two public, so that we can set these last ones in the Inspector. Therefore, we can write:
      public GameObject[] armor;
      private intpiecesOfArmor;
      private Image healthbarFilling;
      public intmaxHealth = 100;
      private int health;
  11. In the Start() function, we have to set up our variables, so let's write:
      void Start () {
        healthbarFilling = this.GetComponent<Image> ();
        health = maxHealth;
        piecesOfArmor = armor.Length;
      }
  12. If the player loses his pieces of armor, there should be a way to regenerate them. We can achieve this by creating the following function:
      public void addArmor(){
        if (piecesOfArmor<armor.Length) {
          piecesOfArmor++;
          updateArmor();
        }
      }
  13. Next, we need to write the damage(int value) function that takes how many health points are taken away from the damage that is applied to the player as a parameter:
      public bool damage(int value){
        if (piecesOfArmor> 0) {
          piecesOfArmor--;
          updateArmor();
          return false;
        }else{
          return damageIgnoringArmor(value);
        }
      }
  14. Furthermore, it could be helpful to have also a function to applied damage ignoring the armor of the player. This is used in games, for instance, for some magic attacks, which hit the player directly. Thus, we can have the following function:
      public booldamageIgnoringArmor(int value){
        health -= value;
        if (health <= 0){  
          health = 0;
          updateHealthbar ();
          return true;
        }
        updateHealthbar ();
        return false;
      }
  15. As we have functions to damage the player, we should also have functions to regenerate life to the player. Therefore, we need to write an addHealth(int value) function, which takes as parameter how many health points will be restored to the player health. The following is the function:
      public void addHealth(int value){
        health += value;
        if (health >maxHealth)
          health = maxHealth;
        updateHealthbar ();
      }
  16. Instead of the other recipes that we have seen so far, we need two update function, one for the health and one for the armor. The following one is for the health:
      public void updateHealthbar(){
        healthbarFilling.fillAmount = health / maxHealth;
      }
  17. And this other one is for the armor:
      public void updateArmor(){
        for (int i=0; i<armor.Length; i++) {
          if(i<piecesOfArmor){
            armor[i].SetActive(true);
          }else{
            armor[i].SetActive(false);
          }
        }
      }
  18. To finish, save our work. We only need to assign the pieces of the armor into the entries of the armor variable, as we did with Implementing a symbolic lives counter recipe.
    How to do it...

How it works...

We have created a linear health bar and named Healthbar with Armor. Then, we created different pieces of armor. Then, we attached our script to Healthbar with Armor.

In the script, we have created five variables. The first one is healthbarFilling and it stores the reference to the Image (Script) component. maxHealth = 100 is the max health that the player can have, and we can set its value in the Inspector, but as default in our script, it has a value of 100. Furthermore, the health variable contains the health currently possessed by the player. The armor variable is an array of game object and it will store all the pieces of armor contained in the Healthbar with Armor. Finally, the piecesOfArmor variable stores the number of pieces of armor currently possessed by the player.

In the Start() function, we set up some variables. In the healthbarFilling variable, we store the Image (Script) component attached in the same game object of this script by calling the this.GetComponent<Image>() function. Then, we set the health variable equal to maxHealth. Finally, we haven't created a public variable that stores the maximum number of pieces of armor directly, so we set the piecesOfArmor variable equal to the length of the armor array, and since we will set this array in the Inspector, it contains all the pieces of armor in the scene. Therefore, its length represents how many pieces of armor there are on this health bar.

The addArmor() function increases the piecesOfArmor variable by one if it has not reached the maximum amount allowed. Then, it calls the updateArmor() function.

The damage(int value) function includes the parameter of how many health points will be taken away from the player after the damage is applied. In fact, it first checks whether the player has some piecesOfArmor, and, if so, decreases it by one, independently from the parameter value and, after calling the updateArmor() function, returns false; this means that the player is still alive. Otherwise, it will call the damageIgnoringArmor(int value) function passing value as a parameter.

The damageIgnoringArmor(int value) function includes the parameter of how many health points will remain when the damage applied. Then, it decreases health by value and checks to see whether the player is still alive. If the player is still alive, it will return false, otherwise return true. After this, the updateHealthbar() function is called to update the user interface.

There is also a function to addHealth(int value) to the player. It increases health by value, if it exceeds maxHealth, then it set health equal to maxHealth, and, finally, calls the updateHealthbar() function to update the user interface.

In the updateHealthbar() function, we set healthbarFilling equal to the ratio between health and maxHealth.

Finally, in the updateArmor() function, we set active or no each pieces of armor according to the piecesOfArmor variable, through a for-cycle, very similar to the one in Implementing a linear health bar recipe.

As last step, we assigned each pieces of armor we have created to the entries of our armor array.

See also

  • If the design of our game doesn't require a health bar with an armor, we should have a look at Implementing a linear health bar and Implementing a radial health bar recipes.
  • For other kind of health bars, see Using multiple bars to make a multibar and Developing a kingdom hearts health bar style.
..................Content has been hidden....................

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