Advertisement
Pro_Unit

Health

Jan 7th, 2021
1,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using UniRx;
  2. using UnityEngine;
  3.  
  4. public class Health : MonoBehaviour
  5. {
  6.     [SerializeField] private int _maxHealth = 100;
  7.     public GameObject Owner { get; set; }
  8.  
  9.  
  10.     public int MaxHealth
  11.     {
  12.         get => _maxHealth;
  13.         set => _maxHealth = value;
  14.     }
  15.  
  16.     private int _currentHealth;
  17.  
  18.     public int CurrentHealth
  19.     {
  20.         get => _currentHealth;
  21.         private set
  22.         {
  23.             _currentHealth = Mathf.Clamp(value, 0, MaxHealth);
  24.  
  25.             OnValueChanged.OnNext(Value);
  26.         }
  27.     }
  28.  
  29.     public float Value => _maxHealth != 0 ? (float) _currentHealth / _maxHealth : 0f;
  30.     public bool IsEmpty => Value == 0f;
  31.     public Subject<float> OnValueChanged { get; } = new Subject<float>();
  32.     public Subject<Health> OnEmpty { get; } = new Subject<Health>();
  33.     public Subject<GameObject> OnDamaged { get; } = new Subject<GameObject>();
  34.  
  35.     private void OnEnable()
  36.     {
  37.         ResetCurrentHealth();
  38.     }
  39.  
  40.     public void TakeDamage(int damage, GameObject damageOwner = null)
  41.     {
  42.         CurrentHealth -= damage;
  43.  
  44.         OnDamaged.OnNext(damageOwner);
  45.  
  46.         if (CurrentHealth == 0)
  47.         {
  48.             OnEmpty.OnNext(this);
  49.         }
  50.     }
  51.  
  52.     public void ResetCurrentHealth()
  53.     {
  54.         CurrentHealth = MaxHealth;
  55.     }
  56.  
  57.     [ContextMenu("Kill")]
  58.     private void Kill()
  59.     {
  60.         TakeDamage(_maxHealth);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement