Health, damage and hit feedback
Assets/
Scenes/
Arena.unity
Scripts/
Project settings
you already havethis lesson adds
You have skills that deal damage, but nothing to hit and no way to see that it worked. A hit the player cannot feel does not exist.
Three signals sell a hit: a number that pops, a body that flashes, and a bar that drops.
Step 1 — something to hit
- 1
Create a Capsule, name it Dummy, give it a red material and put it 6 m in front of the Knight. Yes — it is the same kind of capsule the Knight itself was at the start of this tab.
- 2
Create a layer called Enemy: , then assign it to the Dummy.
- 3
Attach CharacterStats to it and set maxHealth to 120.
- 4
Set the Enemy Layers mask on the Knight's SkillCaster to Enemy only — now Q, E and R hit the dummies and never the Mage or the Archer.
- 5
Duplicate the dummy twice and spread the three around the player.
Step 2 — an event, not a poll
The health bar must not check the health every frame. Instead, CharacterStats announces when health changed, and whoever cares listens.
using System;
using UnityEngine;
// ... inside CharacterStats
/// current, max
public event Action<float, float> OnHealthChanged;
public event Action OnDied;
public void TakeDamage(float rawDamage)
{
if (!IsAlive) return;
float reduced = Mathf.Max(1f, rawDamage - finalDefense);
currentHealth = Mathf.Max(0f, currentHealth - reduced);
OnHealthChanged?.Invoke(currentHealth, finalMaxHp); // tell the listeners
DamagePopup.Spawn(transform.position + Vector3.up * 2f, reduced);
if (!IsAlive)
{
OnDied?.Invoke();
Die();
}
}
public void Heal(float amount)
{
if (!IsAlive) return;
currentHealth = Mathf.Min(finalMaxHp, currentHealth + amount);
OnHealthChanged?.Invoke(currentHealth, finalMaxHp);
}✓ Event
✖ Update() polling
Step 3 — the health bar above the head
- 1
On the Dummy, add a child and set Render Mode = World Space.
- 2
Set the Canvas RectTransform to width 120, height 20, scale 0.01, position Y = 2.4.
- 3
Scale 0.01 turns 120 UI pixels into 1.2 metres — without it the bar is the size of a building.
- 4
Inside it put two Images: a dark background, and a red Fill with Image Type = Filled, Horizontal.
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
[SerializeField] private CharacterStats stats;
[SerializeField] private Image fill;
[SerializeField] private Image trailing; // the slower amber bar
[SerializeField] private float trailSpeed = 1.2f;
private Camera cam;
private float target = 1f;
void Awake() => cam = Camera.main;
void OnEnable()
{
stats.OnHealthChanged += Redraw;
stats.OnDied += () => gameObject.SetActive(false);
}
void OnDisable() => stats.OnHealthChanged -= Redraw; // always unsubscribe
void Redraw(float current, float max)
{
target = max <= 0f ? 0f : current / max;
fill.fillAmount = target; // snaps
}
void LateUpdate()
{
// the trailing bar eases down — this is what makes damage readable
trailing.fillAmount = Mathf.MoveTowards(trailing.fillAmount, target, trailSpeed * Time.deltaTime);
// always face the camera
transform.rotation = cam.transform.rotation;
}
}Step 4 — floating damage numbers
using UnityEngine;
using TMPro;
public class DamagePopup : MonoBehaviour
{
private static DamagePopup prefab;
[SerializeField] private TextMeshProUGUI label;
[SerializeField] private float lifeTime = 0.8f;
[SerializeField] private float riseSpeed = 1.6f;
private float age;
public static void Spawn(Vector3 worldPos, float amount)
{
if (prefab == null)
prefab = Resources.Load<DamagePopup>("DamagePopup"); // Assets/Resources/DamagePopup.prefab
if (prefab == null) return;
DamagePopup p = Instantiate(prefab, worldPos, Quaternion.identity);
p.label.text = Mathf.RoundToInt(amount).ToString();
// a little scatter so two hits never overlap
p.transform.position += new Vector3(Random.Range(-0.3f, 0.3f), 0f, 0f);
}
void Update()
{
age += Time.deltaTime;
transform.position += Vector3.up * riseSpeed * Time.deltaTime;
transform.rotation = Camera.main.transform.rotation;
float t = age / lifeTime;
label.alpha = 1f - t; // fade out
transform.localScale = Vector3.one * (1f + 0.3f * (1f - t));
if (age >= lifeTime) Destroy(gameObject);
}
}The white flash
using System.Collections;
using UnityEngine;
public class HitFlash : MonoBehaviour
{
[SerializeField] private CharacterStats stats;
[SerializeField] private Renderer[] renderers;
[SerializeField] private float duration = 0.09f;
private Color[] original;
void Awake()
{
original = new Color[renderers.Length];
for (int i = 0; i < renderers.Length; i++)
original[i] = renderers[i].material.color;
}
void OnEnable() => stats.OnHealthChanged += (_, __) => { StopAllCoroutines(); StartCoroutine(Flash()); };
IEnumerator Flash()
{
foreach (Renderer r in renderers) r.material.color = Color.white;
yield return new WaitForSeconds(duration);
for (int i = 0; i < renderers.Length; i++) renderers[i].material.color = original[i];
}
}0.09 s is the sweet spot. Shorter and nobody sees it; longer and the enemy looks like a strobe light.
Reading .material creates a per-object copy of the material. That is what lets one enemy flash without flashing all of them.
Combine the flash with the 0.05 s hit-stop from the VFX lesson and even a capsule feels good to punch.