Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my game over screen not showing when current health is 0?

I am busy creating a health system and created a game over screen to show when current health is 0/player is dead.
But the game over screen is not showing (I don’t know much about if)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;

public class HealthSystem : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;

    public HealthBar healthBar;
    public GameObject gameOver;

    public bool damage;

    // Start is called before the first frame update
    void Start()
    {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    void TakeDamage(int damage)
    {
        currentHealth -= damage;

        healthBar.SetHealth(currentHealth);
    }
    
    public void GameOver()
    {
        if (currentHealth == 0)
        {
            gameOver.SetActive(true);
        }
    }

    public void RestartButton()
    {
        SceneManager.LoadScene("Playground");
    }
    
    public void OnDamage(InputValue value)
    {
        DamageInput(value.isPressed);
        TakeDamage(10);
    }

    public void DamageInput(bool newDamageState)
    {
        damage = newDamageState;
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are nowhere calling GameOver() in your code. Every time you decrement currentHealth(), check if it reached zero and do the necessary. For this, call GameOver() in your TakeDamage() method

void TakeDamage(int damage)
{
    currentHealth -= damage;
    
    GameOver();

    healthBar.SetHealth(currentHealth);
}

Also, check if currentHealth is less than or equal to 0, not just 0

public void GameOver()
{
    if (currentHealth <= 0)
    {
        gameOver.SetActive(true);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading