Skip to content

Instantly share code, notes, and snippets.

@nonathaj
Created August 19, 2015 21:51
Show Gist options
  • Save nonathaj/2c0ca0e764a473cc92cc to your computer and use it in GitHub Desktop.
Save nonathaj/2c0ca0e764a473cc92cc to your computer and use it in GitHub Desktop.
Health script and DestroyWhenDead
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(HasHealth))]
public class DestroyWhenDead : MonoBehaviour
{
HasHealth health;
///Lazy getter is safe here, because we used RequireComponent
public HasHealth Health {
get {
if (health == null)
health = GetComponent<HasHealth>();
return health;
}
}
void Awake()
{
//AddListener takes in a UnityAction, which can accept any function that matches it's interface
Health.OnDeath.AddListener(DestroyObject);
//inline delegates are also accepted
//Health.OnDeath.AddListener(delegate () { Destroy(gameObject); });
}
void DestroyObject()
{
Destroy(gameObject);
}
}
using UnityEngine;
using UnityEngine.Events;
public class HasHealth : MonoBehaviour
{
[SerializeField]
float maxHealth = 100f;
public float MaxHealth {
get { return maxHealth; }
set { maxHealth = value; }
}
protected float currentHealth;
public virtual float Health{
get{ return currentHealth; }
set{
bool wasAlive = IsAlive;
currentHealth = Mathf.Clamp(value, 0f, MaxHealth);
OnHealthChanged.Invoke();
if (wasAlive && !IsAlive)
OnDeath.Invoke();
else if (!wasAlive && IsAlive)
OnAlive.Invoke();
}
}
/// <summary>
/// returns a percent float between 0f and 1f
/// </summary>
public float HealthPercent { get { return Health / MaxHealth; } }
///Called whenever this has health returns to life (called once in Awake)
[SerializeField]
UnityEvent onAlive;
public UnityEvent OnAlive { get { return onAlive; } }
///Called whenever the health is updated
[SerializeField]
UnityEvent onHealthChanged;
public UnityEvent OnHealthChanged { get { return onHealthChanged; } }
///Called whenever the health is updated and the object is now dead
[SerializeField]
UnityEvent onDeath;
public UnityEvent OnDeath { get { return onDeath; } }
public bool IsAlive{ get { return Health > 0; } }
public virtual void Awake()
{
ResetHealth();
}
public virtual void TakeDamage(float damage)
{
Health -= damage;
}
public virtual void Heal(float amount)
{
Health += amount;
}
public void ResetHealth()
{
Health = maxHealth;
}
public void Kill()
{
TakeDamage(Health);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment