Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Last active December 31, 2016 02:20
Show Gist options
  • Save unity3dcollege/e2583dfda2554d20f3fb832a6dc291cf to your computer and use it in GitHub Desktop.
Save unity3dcollege/e2583dfda2554d20f3fb832a6dc291cf to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using UnityEngine;
public class NumberOfHitsHealth : MonoBehaviour, IHealth
{
[SerializeField]
private int healthInHits = 5;
[SerializeField]
private float invulnerabilityTimeAfterEachHit = 5f;
private int hitsRemaining;
private bool canTakeDamage = true;
public event Action<float> OnHPPctChanged = delegate(float f) { };
public event Action OnDied = delegate { };
public float CurrentHpPct
{
get { return (float) hitsRemaining / (float) healthInHits; }
}
private void Start()
{
hitsRemaining = healthInHits;
}
public void TakeDamage(int amount)
{
if (canTakeDamage)
{
StartCoroutine(InvunlerabilityTimer());
hitsRemaining--;
OnHPPctChanged(CurrentHpPct);
if (hitsRemaining <= 0)
OnDied();
}
}
private IEnumerator InvunlerabilityTimer()
{
canTakeDamage = false;
yield return new WaitForSeconds(invulnerabilityTimeAfterEachHit);
canTakeDamage = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment