using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerHealth : MonoBehaviour
{
//config params
[SerializeField] float maxBars = 20;
float playerMaxHealth;
float currentHealth;
int healthBarDisplay;
TextMeshProUGUI myText;
//cached references
Player player;
// Start is called before the first frame update
void Start()
{
player = FindObjectOfType<Player>();
myText = GetComponent<TextMeshProUGUI>();
playerMaxHealth = player.DisplayHealth();
OutputHealth();
}
// Update is called once per frame
void Update()
{
OutputHealth();
}
private void OutputHealth()
{
CalculateAndOuputHealth(); // you can add a run condition
}
private void CalculateAndOuputHealth()
{
myText.text = "";
currentHealth = player.DisplayHealth();
healthBarDisplay = Mathf.RoundToInt((currentHealth / playerMaxHealth) * maxBars) ;
for(int i = 0; i < healthBarDisplay; i++)
{
myText.text += "|"; // use any character you prefer (in quotes)
}
}
}
And in Player.cs add a function
public int DisplayHealth()
{
return health;
}
I MacGyvered my own health bar code. Tag this script onto a TextMeshPro game object and watch it work its magic. You’ll have to also tweak the spacing between characters on your object to make it work.