using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Damageable : MonoBehaviour { #if (UNITY_EDITOR) // ONLY FOR DEBUG USE [SerializeField] private bool selfDamage = false; #endif Animator animator; [SerializeField] private int _maxHealth = 100; [SerializeField] private int _health = 100; [SerializeField] private bool _isAlive = true; [SerializeField] private bool isInvincible = false; private float timeSinceHit = 0f; public float invincibilityTime = 0.25f; public AudioClip hitSound; public AudioClip healSound; public AudioClip deathSound; public int MaxHealth { get { return _maxHealth; } set { _maxHealth = value; } } public int Health { get { return _health; } set { if (value > MaxHealth) { _health = MaxHealth; } else { _health = value; } if (value <= 0) { IsAlive = false; if (deathSound != null) { SoundManager.instance.PlaySoundAtPoint(gameObject, deathSound.name); } } } } public bool IsAlive { get { return _isAlive; } private set { _isAlive = value; animator.SetBool(AnimationStrings.isAlive, value); } } private void Awake() { //Health = MaxHealth; animator = GetComponent(); } private void Update() { if (isInvincible) { if (timeSinceHit > invincibilityTime) { isInvincible = false; timeSinceHit = 0; } else { timeSinceHit += Time.deltaTime; } } #if (UNITY_EDITOR) if (selfDamage) { Hit(10); } #endif } public void Hit(int damage) { if (IsAlive && !isInvincible) { int actualDamageAmount = Mathf.Min(damage, Health); Health -= actualDamageAmount; isInvincible = true; CharacterEvents.characterDamaged.Invoke(gameObject, actualDamageAmount); if (hitSound != null) { SoundManager.instance.PlaySoundAtPoint(gameObject, hitSound.name); } } } public bool Heal(int healAmount) { bool result = false; if (IsAlive && Health < MaxHealth) { int actualHealAmount = Mathf.Min(healAmount, MaxHealth - Health); Health += actualHealAmount; CharacterEvents.characterHealed.Invoke(gameObject, actualHealAmount); result = true; if (healSound != null) { SoundManager.instance.PlaySoundAtPoint(gameObject, healSound.name); } } return result; } }