GameDev.CoreSystems/Scripts/Damageable.cs

88 lines
2.3 KiB
C#

using UnityEngine;
using UnityEngine.Events;
namespace GameDev.CoreSystems
{
public class Damageable : MonoBehaviour, IDamageable
{
[Header("RuntimeSet")]
[SerializeField] private SoDamageableRuntimeSet _activeDamageableRuntimeSet;
[field: Header("Health")]
[field: SerializeField] public int CurrentHealth { get; private set; }
[field: SerializeField] public int MaxHealth { get; private set; }
[field: Header("Modifiers")]
[field: SerializeField] public bool IsInvulnerable { get; private set; }
public UnityEvent DeathEvent;
/// <summary>
/// Used to ensure only one damage dealer gets the kill score
/// </summary>
private bool _isAlreadyDead;
private void OnEnable()
{
_activeDamageableRuntimeSet.Add(this);
}
private void OnDisable()
{
_activeDamageableRuntimeSet.Remove(this);
}
#region Methods
public void ModifyHealth(int healthChange, GameObject source)
{
var receivingDamage = healthChange < 0;
var receivingHealing = healthChange > 0;
if (IsInvulnerable && receivingDamage) return;
CurrentHealth += healthChange;
source.TryGetComponent(out Weapon weapon);
if (weapon != null && !_isAlreadyDead)
{
weapon.IncrementDamageDealt(-healthChange);
}
if (CurrentHealth > 0 || _isAlreadyDead) return;
_isAlreadyDead = true;
if (weapon != null)
{
weapon.IncrementKillCount();
}
print($"{transform.parent.parent.name} died");
DeathEvent.Invoke();
}
#endregion
#region Setters
public void SetCurrentHealth(int newHealth) => CurrentHealth = newHealth;
public void SetMaxHealth(int newHealth) => MaxHealth = newHealth;
public void SetInvulnerable(bool newState) => IsInvulnerable = newState;
#endregion
#region Getters
public int GetCurrentHealth() => CurrentHealth;
public int GetMaxHealth() => MaxHealth;
public float GetHealthFactor() => (float)CurrentHealth / (float)MaxHealth;
#endregion
}
}