Search Unity

Question Healthbar does not slide when damage taken

Discussion in 'Getting Started' started by ducklanks, Feb 15, 2022.

  1. ducklanks

    ducklanks

    Joined:
    Jan 23, 2022
    Posts:
    10
    I followed brackeys tutorial on how to do health bars but when I take damage the bar doesn't go down it just disappears when it reaches zero how do I fix this here are the two codes I used. Help would be greatly appreciated as I am stupid.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class healthbar : MonoBehaviour
    7. {
    8.  
    9.     public Slider slider;
    10.  
    11.     public void setmaxhealth(int health)
    12.     {
    13.         slider.maxValue = health;
    14.         slider.value = health;
    15.     }
    16.  
    17.     public void sethealth(int health)
    18.     {
    19.         slider.value = health;
    20.     }
    21.  
    22. }
    23.  


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class Player : MonoBehaviour
    7. {
    8.  
    9.     public int maxhealth = 100;
    10.     public int currenthealth;
    11.     public healthbar healthbar;
    12.  
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.         currenthealth = maxhealth;
    17.         healthbar.setmaxhealth(maxhealth);
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if (Input.GetKeyDown(KeyCode.Space))
    24.         {
    25.             takedamage(20);
    26.         }
    27.  
    28.         void takedamage(int damage)
    29.         {
    30.             currenthealth -= damage;
    31.  
    32.             healthbar.setmaxhealth(currenthealth);
    33.         }
    34.     }
    35. }
     
  2. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446