Health Bar Tutorial

From Unify Community Wiki
Jump to: navigation, search

Health Bar Tutorial

Here is a tutorial about making a health bar for a game. First create C# script and make a public and private int:

private int maxHealth = 100; public int curHealth = 100;

then make a float variable:

private float healthBarlenght;

then in void start type:

healthBarlenght = Screen.width / 2;

in update type:

AdjustcurHealth (0) ;

then make a void OnGUI like this:

void OnGUI () {

   GUI.Box(new Rect(10, 10, healthBarlenght, 20), curHealth "/" maxHealth);

}

then make a void like this:

public void AdjustcurHealth (adj) {

   curHealth += adj;
   if(curHealth < 0)
        curHealth = 0;
   if(curHealth > maxHealth)
        curHealth = maxHealth;
   if(maxHealth < 1)
        maxHealth = 1;
   healthBarlenght = (Screen.width / 2) * (curHealth / (float)maxHealth);

}

then save it off,create a capsule,make it parent of main camera,have main camera in it and attach the script to the capsule. If you press play you should see a health bar in the top right corner. You can change your health in the inspector of the capsule. To make the health bar change from another script then create a new C# script and make a variable:

int GameObject target;

then in the update type this:

if(Input.GetKeyUp(KeyCode.F)){

   Attack();

}

then make a void like this:

public void Attack () {

  <name of health bar script> eh = (<name of health bar script>)target.GetComponent("<name of health bar script>");
        eh.AdjustcurHealth(-1);

}

if you save it off and attatch it to an object. In the inspecter in the script component drag and drop the capsule into the target slot then run and press F your health should go down by 1.

If you want to have something happen when you reach 0 then you could do it by in the health bar script typing in to the AdjustcurHealth void:

if (curHealth = 0) {

   <what you want to be done>

}

And you have a health bar!!!

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox