Skip to content

Instantly share code, notes, and snippets.

@TheMehranKhan
Created October 27, 2023 20:34
Show Gist options
  • Save TheMehranKhan/2968aa57ce0cf349fdddef68fbf23825 to your computer and use it in GitHub Desktop.
Save TheMehranKhan/2968aa57ce0cf349fdddef68fbf23825 to your computer and use it in GitHub Desktop.
A health bar that is represented by a slider UI element.
// Author: themehrankhan
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// A health bar that is represented by a slider UI element.
/// It can be used to display the player's current health in the game.
///
/// To use the health bar, simply attach this script to a game object in your scene
/// and assign the slider UI element to the `slider` public property.
/// You can then change the player's health by calling the `SetHealth()` method.
///
/// The health bar will automatically update its display to reflect the player's current health.
/// </summary>
public class HealthBar : MonoBehaviour
{
/// <summary>
/// The slider UI element that represents the health bar.
/// </summary>
public Slider slider;
/// <summary>
/// Sets the maximum value of the health bar slider.
/// </summary>
/// <param name="maxHealth">The maximum health.</param>
public void SetMaxHealth(int maxHealth)
{
// Set the maximum value of the health bar slider
slider.maxValue = maxHealth;
slider.value = maxHealth;
}
/// <summary>
/// Sets the current value of the health bar slider.
/// </summary>
/// <param name="health">The current health.</param>
public void SetHealth(int health)
{
// Set the current value of the health bar slider
slider.value = health;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment