Create a player health status indicator for the Unity GUI, part 3

November 8, 2012 — Leave a comment

This is the third of a multi-part series that will teach you how to build a player health status indicator for the Unity GUI. If you haven’t already, you should read Part 1 and Part 2. You might also wish to download download the starter assets, which you can then import into Unity.

Introduction

So, we’ve got our health status indicator on the screen and we can manually drag on the Health Width property in the inspector to shrink and expand the green health bar while the game is running. But, of course, we need to be able to change the health by accessing the healthWidth property from some other behavior script in the game.

Let’s imagine a scenario in which an enemy is attacking your hero. Each time the enemy gets within the vicinity of the hero or touches the hero, a script attached to the enemy game object might recognize the collision and send a signal to the health status widget to change.

In today’s post we’ll tell you how to do it and you’ll be learning a simple skill that you’ll use a lot in your Unity games – you will learn how to access global variables or properties in one behavior script from another.

Access the Health Status from Any Behavior Script

First, let’s just get this working and then we’ll break it down to understand what the script is doing. Complete the following steps to see the green health being reduced automatically at runtime:

  • First, make sure that the GameObject that your HealthBarScript is attached to is named “GUI Health”.
  • Next, create a new GameObject and name it ‘Enemy’.
  • Create a new behavior script using Assets > Create > Javascript. Name it ‘EnemyBehaviorScript.’
  • Drag and drop the EnemyBehaviorScript on the Enemy GameObject and make sure that GameObject is in the scene.

Finally paste the following code into the EnemyBehaviorScript, save the script and run the game to see the health shrink away to fatality! If it’s more convenient, you can also just download the EnemyBehaviorScript.js file and import it into Unity.

#pragma strict
 
private var guiHealth : GameObject;
private var healthBarScript: HealthBarScript;
 
/*
Start is called only once in the lifetime of 
the behavior. So, it's a good place to initialize 
things only once.
*/
function Start() {
 
    guiHealth = GameObject.Find("GUI Health");
    healthBarScript = guiHealth.GetComponent("HealthBarScript");
 
    // Set initial value of the health...
 
    // Uncomment the line below and call reduceHealth() in the Update() method to watch health decrease
    healthBarScript.healthWidth = 199;
 
    // Uncomment the line below and call increaseHealth() in the Update() method to watch health increase
    // healthBarScript.healthWidth = -8;
 
}
 
function Update() {
 
   	reduceHealth();
 
   	//increaseHealth();
 
}
 
/*
Only decrease the health bar if it's greater than the min width it should ever be;
because we do not want it decreased beyond the left of its frame.
*/
function reduceHealth() {
   if(healthBarScript.healthWidth > -8) {
       healthBarScript.healthWidth = healthBarScript.healthWidth - 1;
   }   
}
 
/*
Only increase the health bar if it's less than the max width it should ever be;
because we do not want it stretched out beyond its frame.
*/
function increaseHealth() {
   if(healthBarScript.healthWidth < 199) {
       healthBarScript.healthWidth = healthBarScript.healthWidth + 1;
   }
}

How it Works

You may notice that we declared our global variables as private this time.

private var guiHealth : GameObject;
private var healthBarScript: HealthBarScript;

By declaring them global (outside of any function in the script), they are available for use by any function in the script. By declaring them private, we ensure that they will not create properties in the Unity Inspector panel that might distract you or other developers on your team. For this script, they’re not mean to be used in the Inspector.

Next, we have the Start() method.

Oh, by the way…

Did you notice that sometimes we use the word function and sometimes we use the word method? The two words mean essentially the same thing. In JavaScript lingo, they’re commonly referred to as functions. Unity documentation calls them methods. So, the words are interchangeable.

Back to the Start() method…

function Start() {
 
    guiHealth = GameObject.Find("GUI Health");
    healthBarScript = guiHealth.GetComponent("HealthBarScript");
 
    ...
}

When you use a Start() method in a behavior script, it gets called only once in the lifetime of the behavior. So, it’s a good place to initialize objects. In this case, we’re making guiHealth represent the GameObject that can be found in the game by the name ‘GUI Health’. The we make healthBarScript represent the script named ‘HealthBarScript’ that we expect to be attached to the guiHealth GameObject that we just found. Since the HealthBarScript is attached to a GameObject, we need to access the GameObject in the scene first. The, once we have access to it, we can use .getComponent() to get components attached to that object.

Now the next lines are just there to set the initial health. You can comment one out and uncomment the other and vise-versa.

    // Uncomment the line below and call reduceHealth() in the Update() method to watch health decrease
    healthBarScript.healthWidth = 199;
 
    // Uncomment the line below and call increaseHealth() in the Update() method to watch health increase
    // healthBarScript.healthWidth = -8;

You also want to toggle the comments on the reduceHealth() and increaseHealth() calls respectively.

function Update() {

   	reduceHealth();

   	//increaseHealth();

}

By toggling those comments, you can watch the health shrink or grow; just a simple acid-test to prove that it works.

The reduceHealth() and increaseHealth() methods simply add to or subtract from the width of the healthWidth property. They are surrounded by an if condition, which just ensures that the green status bar cannot shrink or grow beyond the decorative frame.

Conclusion

In this post, we taught you how to change the health in the status indicator through code. In particular, we should you how to access properties in one behavior script from another by first accessing the GameObject the script is attached to.

In this three part series, we’ve given you the essential knowledge you need to indicate your player’s health. Of course, you’ll have to take it from here and integrate these principles into your working game. If you have any questions or suggestions for something else you’d like us to cover, please comment.

Until next time, enjoy the craft!

ethan.york

Posts

Write for us!

We pay for great content that helps young and aspiring game makers along the path to mastery. You can earn extra income doing what you love and sharing what you learn! For more information, contact info@mastergamecraft.com.

No Comments

Be the first to start the conversation.

Leave a Reply