Making a Health Bar with Code

I have a damage reciever script, and a health bar script, but I want the health bar to decrease as the player gets hit. How should I do that? Here are my scripts:

Health Bar GUI Script

function OnGUI() {
    GUI.backgroundColor = Color.green;
      GUI.Button(Rect(10,640,510,20),"Health");
}

Damage Reciever Script

var hitPoints = 100.0; 
var detonationDelay = 0.0; 
var explosion : GameObject; 
var deadReplacement : Rigidbody; 

function ApplyDamage (damage : float) { // We already have less than 0 hitpoints, maybe we got killed already? if (hitPoints <= 0.0) return;

hitPoints -= damage;
if (hitPoints <= 0.0) {
    // Start emitting particles
    var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
    if (emitter)
        emitter.emit = true;

    Invoke("DelayedDetonate", detonationDelay);
}
}

function DelayedDetonate () { BroadcastMessage ("Detonate"); }

function Detonate () { // Destroy ourselves Destroy(gameObject);

// Create the explosion
if (explosion)
    Instantiate (explosion, transform.position, transform.rotation);

// If we have a dead barrel then replace ourselves with it!
if (deadReplacement) {
    var dead : Rigidbody = Instantiate(deadReplacement, transform.position, transform.rotation);

    // For better effect we assign the same velocity to the exploded barrel
    dead.rigidbody.velocity = rigidbody.velocity;
    dead.angularVelocity = rigidbody.angularVelocity;
}

// If there is a particle emitter stop emitting and detach so it doesnt get destroyed
// right away
var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
if (emitter) {
    emitter.emit = false;
    emitter.transform.parent = null;
}
Destroy (gameObject);
}

// We require the barrel to be a rigidbody, so that it can do nice physics @script RequireComponent (Rigidbody)

The damage reciever script works. All I need is the damage done using the damage reciever to affect the health bar (shorten the width). Thanks in advance!

Also, if you can tell me how to show a percentage of health, that would help.

You don't have to use the Health Bar script exactly to answer this question. The Damage Reciever script has to stay the same though.

[PR1][1] resolves this as well [1]: https://github.com/Voodooyou/Game-Prototype/pull/1/files#diff-9b363faa7d90c770493f56a947584d0f20603c353b0b346b2b2e261342472bd9R70-R73

>> Also, why do they cause a race condition? Good question. Jitter is caused by both RigidBody and CharacterController moving this object but on different time steps. RigidBody moves your object on FixedUpdate (every 0.02<strike>) while CharacterController moves it on Update(every 1/FPS ~~so it varies all the time). Which one of them wins? Well, winner is totally random in this setup. So you see these components winning and losing the control at random, every frame.~~</strike>

5 Answers

5

It is add in to the Damage Receiver Script.

function OnGUI()
{
    GUI.HorizontalScrollbar(Rect (0,40,200,20), 0, hitPoints,0, 100);
}

I forgot about this answer. This one works. Thanks!

Making a health bar is ridiculously simple in the all new Unity UI. You just need to use a slider to create one and a bit of code. Check this article out [Health Bar Unity 4.6][1] [1]: http://www.thegamecontriver.com/2014/08/unity-46-create-health-bar-hud.html

There are seriously tons of posts on this, with examples for rectangular health bars, circular health bars, anything you could imagine.

Here’s the top Google result for ‘Unity Health Bar’:

http://answers.unity3d.com/questions/17255/how-do-i-make-a-health-bar.html

Next time, check around at least a little bit before posting a question, because otherwise folks like me get grumpy.

I know there are other tutorials and other questions like this, but I need to use that specific damage receiver because other scripts depend on that damage receiver so I need help for THIS receiver. Otherwise I would never had asked this question (And I'm with you, I can't stand when people ask questions that have already been answered).

okay, then I'm not understanding your question. What specifically are you trying to do? Is your issue with trying to access variables or methods in one script from another script?

yeah, that's my issue, I don't know how to link the two scripts so the health bar goes down.

It still leans back, but I'd rather not take any more of your time. Is there a good source you could point me to, so I can try and fix the rest myself?

Not sure if you were only looking to narrow the width…

var scale = 1.0f;

function OnGUI() {
    GUI.backgroundColor = Color.green;
    GUI.Button(Rect(10, 640, 510 * scale, 20), "Health");
}

// Call this to update the health.
// Note: 100.0f should be max.
function SetHealth(health : float) {
    scale = Mathf.Clamp01(health / 100.0f);
}

I've tried everything, so I'm coming back to you. You're right, I'm only trying to narrow the width, and it has to be connected to that damage receiver. Right now, I have one huge script for the player, so the GUI Health Bar will be part of the Health Script. How do I use your script, to make the Health Bar get smaller as the health bar goes down?

Download or merge this PR into your codebase and you will see it fixed.

Belay that, it works. The muzzle was just being jank with the prefab gun for some reason. Setting it to just a regular cube shows it works wonders. Thank you for the help man, I'll never forget that!

yeah, that's my issue, I don't know how to link the two scripts so the health bar goes down.

Alrighty, that's a very reasonable question to ask.

There are a number of ways to link scripts. If you want to do it by hand, create a public variable of type [name of script] and then drop your other script into it in the editor. You can then access public functions in the referenced script like so

otherCode.doSomething();

where otherCode is your reference to the other script and doSomething is your public function.

You can also look into GameObject.Find to get a reference to the game object containing the other function, and then GetComponent to access the script. There are also more advanced things like FindObjectOfType.

Finally, if you just want to send a message to a script in a game object without worrying about what the receiving script is called, you can use SendMessage. Don't know how to use SendMessage, and the script reference is confusing? There are quite a few notes on it here and in the forums.

Best of luck,

Julien

I'm learning. Thank you for showing me how to link scripts but now that scripts are linked, how do I make the health bar decrease for damage?

Here is the solution :

var Health = 100;
var position = Rect (500,15,200,20);

function OnTriggerEnter (Objecte : Collider) {
	if (Objecte.tag == "Obstacle") 
	{
		Health -= 50;
		
	}
}

function Update ()
{
	if (Health <= 0)
	{
		Application.LoadLevel (Application.loadedLevel);
	}
}

 function OnGUI()
{
    GUI.backgroundColor = Color.green;
    GUI.HorizontalScrollbar(position, 0, Health,0, 100);
}

I updated your answer to make the code readable