Yet another health bar request

Hello everyone,

For the last month I searched and tried to implement a health bar in my game.
I had no luck. Even though there are a million tutorials out there, I just didn’t found the correct one. Trust me, I tried about 10-15 code variants.

I need this :

Floating health bar (a bar with color red for example, not a text showing a number) over each of my spawned units (follows the unit, is not set in an area of the screen).
Would be nice to have the code in C#, if not I will try to adapt a JS code.

All I need is this magical piece of code which eludes me for so long. I even bought NGUIText and Health Bar scripts from the Asset Store. No luck as well…

This is not a place to ask for code to be written for you.

You should try and code something yourself but this is how I would go about it:

  1. Either you need to make an Array/List of all your ‘units’ or you should instantiate each unit with the same script attached to it.
  2. Once you have an object that needs a health bar, find its position (or a point above its position) in screen space using Camera.WorldToScreenPoint.
  3. Once you have a point in screen space you can draw a rectangle using GUI.DrawTexture.
  4. Scale the Texture based on the health of the unit

You should probably learn to code this if you wish to make a successful game,

A much better use of this site is to try and code it yourself and ask specific questions on sections of code

Scribe

EDIT:
Attempt at code

int maxHealth;
int currentHealth;
Vector3 ScreenPos;
Texture2D MyTex;
int MaxTextureWidth;


void Update () {
	ScreenPos = Camera.main.WorldToScreenPoint(transform.position+Vector3.up);
}

void OnGUI () {
	GUI.DrawTexture(Rect(ScreenPos.x-((MaxTextureWidth/2.0)*((float)currentHealth/(float)maxHealth)), ScreenPos.y, MaxTextureWidth*((float)currentHealth/(float)maxHealth), 20), MyTex)
}

You have NGUI… so I recommend you this :

good luck.