Files
Infratest/Assets/Code/Example/Platformer/Entity/EntityHealth.cs
T

76 lines
2.1 KiB
C#

using System;
using Code.Infrastructure.EventBus;
using Cysharp.Threading.Tasks;
using Reflex.Attributes;
using UnityEngine;
namespace Code.Example.Platformer.Entity
{
public class EntityHealth : MonoBehaviour
{
private int _health;
private int _maxHealth;
private float _damageThreshold;
public void Setup(int maxHealth, float damageThreshold)
{
_maxHealth = maxHealth;
_health = maxHealth;
_damageThreshold = damageThreshold;
}
public bool IsDead { get; private set; }
private bool _isDamageable = true;
[Inject] private EventBus _eventBus;
public Action<int> OnEntityHeal;
public Action<int> OnEntityDamage;
public Action OnEntityDeath;
private async UniTaskVoid WaitThreshold()
{
await UniTask.WaitForSeconds(_damageThreshold);
_isDamageable = true;
}
public void GiveDamage(int damage)
{
if (!_isDamageable) return;
_health -= damage;
_isDamageable = false;
OnEntityDamage?.Invoke(_health);
if(_health <= 0)
{
IsDead = true;
OnEntityDeath?.Invoke();
}
_eventBus.RaiseEvent<IEntityDamagedHandler>(x=> x.EntityDamaged(gameObject, damage, IsDead));
WaitThreshold().Forget();
}
public void Heal(int heal)
{
if (IsDead) return;
if (_health + heal > _maxHealth) _health = _maxHealth;
else _health += heal;
OnEntityHeal?.Invoke(_health);
_eventBus.RaiseEvent<IEntityHealedHandler>(x=> x.EntityHealed(gameObject, heal));
}
}
public interface IEntityDamagedHandler : IGlobalSubscriber
{
void EntityDamaged(GameObject entity, int damageCount, bool isDied);
}
public interface IEntityHealedHandler : IGlobalSubscriber
{
void EntityHealed(GameObject entity, int healCount);
}
}