- Home /
How to put a health bar above enemy?C#
Hi there!
So, I must feel really stupid or something because I cant seem to figure this out, and I even looked it up.
Basically, I would like a red bar above the enemy that would go down when ever it gets hit. If someone could like... point me in the right direction or help me, that would be great.
Again sorry if I sound like a complete idiot. GUI is not my thing.
-Squizy
Answer by morgan23 · May 15, 2014 at 04:08 PM
BugzergArcade's vids tutorial's he does what your asking.
Thank you so much! I completely forgot about these tutorials! :D
thiers a free version I use it because I don't really like scripting in the ongui method.
Answer by FlaflaTwo · May 15, 2014 at 05:08 PM
One way to do it would be using `Transform.InverseTransformPoint(Vector3)` to transform a world point (i.e., the point in which you want the health bar to "float" on) to screen coordinates. Then you would use Unity's GUI features to draw a health texture for the bar, labels, etc. Here is an example:
public class Bar : MonoBehaviour {
public Transform barWorldCoords;
public Texture barBackground;
public Texture barForeground;
public float health = 1.0f; // From 0.0 (no health) to 1.0 (full health)
void OnGUI() {
Vector3 screenPoint = Transform.InverseTransformPoint(barWorldCoords.position);
// Draw Background
GUI.DrawTexture(new Rect(screenPoint.x-100, screenPoint.y-20, 200, 40),
barBackground, ScaleMode.StretchToFill, true);
// Draw Foreground
GUI.DrawTexture(new Rect(screenPoint.x-100, screenPoint.y-20, 200F*health, 40),
barForeground, ScaleMode.StretchToFill, true,
((barForeground.width*health)/barForeground.height));
}
}
This isn't tested, so it might have bugs, but you should get the general idea from it.
I get a An object reference is required to access a non static member for the InverseTransformPoint
Your answer
![](https://koobas.hobune.stream/wayback/20220613145113im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Creating A GUI health bar 0 Answers
Drawing 4 GUIButton's with a forloop. Need help changing color? 1 Answer
Return to origional position. 2 Answers