Healthbar

PHOTO EMBED

Sun Nov 24 2024 14:43:48 GMT+0000 (Coordinated Universal Time)

Saved by @censored #c#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class HealthBar : MonoBehaviour
{
    public Slider healthSlider;
    public TMP_Text healthBarText;

    HealthSystem playerHealthSystem;
    // Start is called before the first frame update

    private void Awake()
    {
        GameObject player = GameObject.FindGameObjectWithTag("Player");

        if(player == null)
        {
            Debug.Log("player not found or missing tag on player");
        }

        playerHealthSystem = player.GetComponent<HealthSystem>();
    }
    void Start()
    {
        healthSlider.value = CalculateSliderPercentage(playerHealthSystem.currentHealth, playerHealthSystem.maxHealth);
        healthBarText.text = "HP " + playerHealthSystem.currentHealth + " / " + playerHealthSystem.maxHealth;
    }

    private void OnEnable()
    {
        playerHealthSystem.OnHealthChanged.AddListener(OnPlayerHealthChanged);
    }

    private void OnDisable()
    {
        playerHealthSystem.OnHealthChanged.RemoveListener(OnPlayerHealthChanged);
    }

    private float CalculateSliderPercentage(int currentHealth, int maxHealth)
    {
        return currentHealth / maxHealth;
    }

    private void OnPlayerHealthChanged(int newHealth, int maxHealth)
    {
        healthSlider.value = CalculateSliderPercentage(newHealth, maxHealth);
        healthBarText.text = "HP " + newHealth + " / " + maxHealth;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
content_copyCOPY

before change

https://pastecode.io/