- Home /
Health bar goes negative
Does anyone know how to make the health bar stop at zero? Sometimes the player dies but most of the time when the player is holding a weapon the health bar goes negative. My code: public int healths = 10; // Start is called before the first frame update void Start() {
}
// Update is called once per frame
void Update()
{
if(healths == 0)
{
SceneManager.LoadScene("lose");
Cursor.visible = false;
Cursor.lockState = CursorLockMode.None;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Enemy")
{
healths = healths - 1;
}
if(collision.gameObject.tag == "Lava")
{
healths = healths - 1;
}
}
}
The health bar code: Text E; public GameObject Player; // Start is called before the first frame update void Start() { E = GetComponent(); }
// Update is called once per frame
void Update()
{
E.text = "Health: " + Player.GetComponent<E>().healths;
}
}
Answer by pauldarius98 · Mar 03, 2021 at 07:09 AM
The best thing that you can do is to use Math.Clamp. Math.Clamp will take a value, a minimum value and a maximum value and it will return the value clamped between the given minimum and maximum and thus you can make sure that your value never goes below 0 and never exceeds maximum health. Code:
healths = Mathf.Clamp(healths - 1, 0, 10); //change 10 to whatever maximum health is
Answer by rh_galaxy · Mar 03, 2021 at 05:25 AM
You should guard against negative values for health on all places where you take a hit. Maybe the player collides with multiple enemies, or both lava and enemy the same frame...
if(healths>0) healths -= 1;
In your case if the healths is between 0 and 1, it will still drop to a negative value
Your answer
![](https://koobas.hobune.stream/wayback/20220613030114im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Player health dropping far to fast 1 Answer
Trying to make a unique type of health 'bar' 1 Answer
health bar referencing another scripts variable 3 Answers
Enemy Health Bar Fill (Unity2D) 2 Answers