Last active
December 31, 2016 02:20
-
-
Save unity3dcollege/e2583dfda2554d20f3fb832a6dc291cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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