- Home /
Why isn't my health script working ?
I want a script where when my players health reaches 0 it sends them to a game over screen. (This is in the same script as the healthbar)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Health : MonoBehaviour {
//health reference
private const float MAX_HEALTH = 100f;
public float health = MAX_HEALTH;
//health bar
private Image healthBar;
// Start is called before the first frame update
void Start()
{
healthBar = GetComponent<Image>();
}
// Update is called once per frame
void Update()
{
healthBar.fillAmount = health / MAX_HEALTH;
}
// de a t h
public void DealDamage(float damage)
{
if ((health -= damage) < 0f)
{
Die();
}
}
private void Die()
{
SceneManager.LoadScene("GameOver");
}
}
Can you share a bit more detail about the system that uses the method DealDamage?
Answer by Stevenm462 · Jun 09, 2021 at 02:54 PM
The issue might be because your checking to see if the health is less than 0. If your health can only go to 0 than it is equal to 0 not less then. you could replace you < 0 with <= 0 or == 0
Answer by Harry_Drew · Jun 09, 2021 at 09:49 AM
I don't think its working because your doing heath -= damage in the if statement. Try replacing it with this:
public void DealDamage(float damage)
{
health -= damage;
if (health < 0f)
{
Die();
}
}
If this doesn't work just check that the scene that your trying to load is called "GameOver" Btw: can you change the name of the question because "Why isnt this working" is a bit generic :) Thanks
That's not really an issue and should work just fine. As you said, it's absolutely unclear what the problem is. Maybe because he has his health variable serialized, it does not have his desired starting value? Who knows...
Answer by Rayvinz · Jun 10, 2021 at 07:42 AM
I fixed it by adding a current health and a max health idk why but it works now.