Health Bar Code

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.

3 Likes

Noob here. Thanks for this!

I tried to implement your code and it’s not working for me lol.

Am I supposed to create an empty game object and add component Text Mesh Pro Input Field, text, UI? Or is this a UI - Text Mesh Pro?

1 Like

UI - Text Mesh Pro

Extra :
I designed this to be plug-and-play so just check if you’ve followed all the steps-

It’s a UI - Text Mesh Pro Object - add the script, adjust character spacing.

Play with it a bit if you can’t find a solution.

Well done on making your own health bar and sharing it with the community :slight_smile: