Skip to main content

002. Unity3d Tutorial - Health Bar 2/2

See video

We will finish off our health bar system for our player, and then copy it so that it will work for our enemy as well.

Tags:

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Offline
Joined: May 11 2011

i like how this is two tutorials at once. (My you tube is Rokstar234 if you wondering who i am)this is a C# tutorial cause it teaches you the basic Syntax of C# scripting And A very good detailed Unity tutorial. and most of the series can be done in free edition while other may require pro. :)

Offline
Joined: Mar 19 2012

Thanks Petey!

Offline
Joined: Apr 14 2012

Hi I've inputted this tutorial twice now and I still can't get the health bar to come up. this is my script:

using UnityEngine;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;

public float healthBarLength;

// Use this for initialization
void Start () {
healthBarLength = Screen.width / 2;
}

// Update is called once per frame
void Update () {
AddjustCurrentHealth (0);
}
void onGUI(){
GUI.Box(new Rect(10, 10, healthBarLength, 20), curHealth + "/" + maxHealth);
}

public void AddjustCurrentHealth(int adj) {
curHealth += adj;

if(curHealth < 0)
curHealth = 0;

if (curHealth > maxHealth)
maxHealth = 1;

healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
}
}

Am I doing something wrong? I've gone over it but maybe I missed something.

Thanks. GREAT TUTORIALS.

Offline
Joined: Apr 17 2012

Hey Matt, it looks like you typed:

void onGUI()

when the Unity function you need to call is

void OnGUI()

I made a worse mistake, had OnGui, in this and the last video. Took me a while to notice. Hope that helps.

Offline
Joined: May 1 2012

Hello Petey ! Can you explain the purpose of putting (float) infront of the maxHealth value inside the AdjustCurrentHealth function?

Petey's picture
Offline
Joined: Feb 3 2010

IT is referred to as type casting. It will make the result a float instead of an int

Petey's picture
Offline
Joined: Feb 3 2010

IT is referred to as type casting. It will make the result a float instead of an int

Offline
Joined: May 1 2012

Oh I see. So do we have to use type casting in order to get a float from the division of two int values? Seems logical but I've never thought about it. I'm a newbie at programming :p. Thanks for yor help!

ps Had I not put the (float) infront of the maxHealth value, would the output be 0 if I tried to reduce the curHealth from the Inspector?