I expanded on my slider approach from last lecture to show an enemy equivalent to the player health bar with percentage (can’t figure out why the formatting isn’t working though, so if you figure it out, let me know I’ll update this post).
It is not on the screen if target == null on the player’s fighter script. To do this, I had to add a dead check to the update on fighter to make target null if we kill the target, that way the health bar stops displaying on enemy death.
void Update()
{
timeSinceLastAttack += Time.deltaTime;
if (target != null && target.IsDead()) target = null;
if (target == null) return;
if (CanAttack(target.gameObject))
{
MoveToAttack();
}
}
Duplicate your player’s health bar like so and start enemy health bar inactive
here is the newly revised HealthDisplay.cs script on the main hud object, I always use Text Mesh Pro, so that’s what’s in this script, but you can adjust that if your don’t use TMPro.
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;
using RPG.Combat;
using RPG.Stats;
namespace RPG.Resources
{
public class HealthDisplay : MonoBehaviour
{
[Space(10)]
[Header("Player Health")]
[SerializeField] Slider healthSlider;
[SerializeField] TextMeshProUGUI healthText;
Health health;
Fighter fighterScript;
[Space(10)]
[Header("Enemy Health")]
[Space(20)]
[SerializeField] GameObject enemyHealthDisplay;
[SerializeField] Slider enemyHealthSlider;
[SerializeField] TextMeshProUGUI enemyHealthText;
Health enemyHealth;
private void Awake()
{
health = GameObject.FindWithTag("Player").GetComponent<Health>();
fighterScript = health.gameObject.GetComponent<Fighter>();
}
IEnumerator Start()
{
yield return new WaitForSeconds(0.1f);
SetSliderMaximumValue();
}
private void SetSliderMaximumValue()
{
healthSlider.maxValue = health.GetHealthPoints();
}
void Update()
{
SetSliderValue();
SetHealthText();
if(fighterScript.GetTarget() != null)
{
AssignEnemyToEnemyHealth();
SetEnemySliderMaximumValue();
SetEnemySliderValue();
SetEnemyHealthText();
}
else
{
enemyHealth = null;
enemyHealthDisplay.SetActive(false);
}
}
// PLAYER
private void SetSliderValue()
{
healthSlider.value = health.GetHealthPoints();
}
private void SetHealthText()
{
var healthPercent = (healthSlider.value / healthSlider.maxValue * 100).ToString();
healthText.text = string.Format("{0:0.0}%", healthPercent);
}
// ENEMY
private void AssignEnemyToEnemyHealth()
{
enemyHealth = fighterScript.GetTarget().GetComponent<Health>();
enemyHealthDisplay.SetActive(true);
}
private void SetEnemySliderMaximumValue()
{
enemyHealthSlider.maxValue = enemyHealth.gameObject.GetComponent<BaseStats>().GetHealth();
}
private void SetEnemySliderValue()
{
enemyHealthSlider.value = enemyHealth.GetHealthPoints();
}
private void SetEnemyHealthText()
{
var enemyHealthPercent = (enemyHealthSlider.value / enemyHealthSlider.maxValue * 100).ToString();
enemyHealthText.text = string.Format("{0:0.0}%", enemyHealthPercent);
}
}
}