Health bar help
Ok so I made a simple health bar system, and for demo purposes, I'm having the character's health decrease over time. Here is my code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HealthMeterManagement : MonoBehaviour {
public Image Bar;
public Text Text;
public float max_health = 100f;
public float cur_health = 0f;
//Use this for initialization
void Start()
{
// Initialize the health that is given
cur_health = max_health;
InvokeRepeating("decreaseHealth", 0f, 2f);
}
void Update()
{
}
void decreaseHealth()
{
//Subtract the health at the following rate
//Check if the health is 0 before we do any damage
if (cur_health >= 0)
{
cur_health -= 1300.23423423f;
}
//make a new variable and divide the current health my the maximum health
//this is because the fill value goes from 0 to 1
float calc_health = cur_health / max_health; // 70 / 100 = 0.7
SetHealth(calc_health);
//Change the color of the health bar
if (cur_health != 0 && cur_health <= max_health / 1.6 && cur_health > max_health / 2.9 ) // on the scale of 1000, if health <= 625 and is greater than 345, do the following
{
Bar.color = new Color32(171, 162, 53, 255);
}
else if (cur_health != 0 && cur_health <= max_health / 2.9) // on the scale of 1000, if health <= 625, do the following
{
Bar.color = new Color32(158, 25, 25, 255);
}
}
void SetHealth (float myHealth)
{
//defill the bar based on the current health
Bar.fillAmount = myHealth;
//change the text to display the amount of health
Text.text = (int)cur_health + "/1000";
}
}
The reason I set damage to be 1300.23423423 is because
1) I Want to make sure that no matter what amt of damage my character is taken, the text will remain as whole numbers, for the simplicity of the user 2) It's to simulate an overpowered enemy (if in some instance you went to a level where the enemies do tons of damage if you aren't a high enough level)
The problem is I want the health to stay at zero if it goes below zero. I don't know how to do that because if the enemy does an immediate 130.23423423 amount of damage, there is no where in place of the code to check in advance for that variable to change to 0. Or at least, from what I know of.
So just to be clear: you want the 'cur_health' variable to remain at a $$anonymous$$imum of 0, correct? Or am I misunderstanding?
Answer by BlackSnow_2 · Sep 02, 2015 at 06:51 AM
if (cur_health < 0)
{
cur_health = 0;
}
As a side note, to keep a string as an int instead of:
Text.text = (int)cur_health + "/1000";
Use this:
Text.text = cur_health.ToString ("f0") + "/1000";
That will (AFAIK) keep the text displayed limited to an Int. Use "'f1'" for 1 decimal, "'f2'" for 2 and so on.
Your answer
Follow this Question
Related Questions
Health bar/damage script not working. Please help. 0 Answers
Apply Damage Universally 0 Answers
How to make my enemies damage player? 0 Answers
Damage not working properly 1 Answer