Files
2025-05-13 05:19:58 +03:00

66 lines
1.5 KiB
C#

using UnityEngine;
using System.Collections;
public delegate void HealthDelegate();
public delegate void HealthDamageDelegate(float damage, Object source, Vector3? worldPoint);
public class Health : MonoBehaviour {
public float value = 100;
public bool destroyed = false;
public event HealthDelegate Destroyed;
public event HealthDamageDelegate DamageApplied;
public RandomSoundPlayer deathPlayer;
protected virtual void OnDamageApplied(float damage, Object source, Vector3? worldpoint) {
HealthDamageDelegate handler = DamageApplied;
if (handler != null) {
handler(damage, source, worldpoint);
}
}
public bool Dead{
get{return value <= 0.0f;}
}
protected virtual void OnDestroyed ()
{
if (deathPlayer != null) {
deathPlayer.Play();
}
var handler = Destroyed;
if (handler != null)
handler ();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI(){
var pt = Camera.main.WorldToScreenPoint(transform.position);
pt.y = Camera.main.pixelHeight - pt.y;
//GUI.Label(new Rect(pt.x,pt.y, 100,30), "Health: " + health);
}
public void ApplyDamage(float damage, Object source = null, Vector3? worldPoint = null){
if(!destroyed) {
Debug.LogFormat("Apply damage {0} to object {1}", damage, name);
OnDamageApplied(damage, source, worldPoint);
value -= Mathf.Clamp(Mathf.Abs(damage), 0, value);
if(value <= 0.0f){
destroyed = true;
OnDestroyed();
}
}
}
}