78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
namespace BITKit.Entities
|
|
{
|
|
public interface IHealthCallback
|
|
{
|
|
void OnSetAlive(bool alive);
|
|
void OnSetHP(int hp);
|
|
}
|
|
public class EntityHealth : EntityComponent
|
|
{
|
|
[Header(Constant.Header.Settings)]
|
|
public int healthPoint = 100;
|
|
[Header(Constant.Header.Events)]
|
|
public UnityEvent<bool> onSetAlive = new();
|
|
[Header(Constant.Header.InternalVariables)]
|
|
bool isAlive;
|
|
public override void OnAwake()
|
|
{
|
|
entity.AddListener<DamageMessage>(OnDamage);
|
|
}
|
|
public override void OnStart()
|
|
{
|
|
isAlive = healthPoint >= 0;
|
|
OnSetAlive(isAlive);
|
|
OnHealthPointChanged(0, healthPoint);
|
|
}
|
|
void OnHealthPointChanged(int old, int newHP)
|
|
{
|
|
var _isAlive = newHP >= 0;
|
|
if (_isAlive != isAlive)
|
|
{
|
|
OnSetAlive(isAlive = _isAlive);
|
|
}
|
|
//entity.Invoke<int>(_onSetHP, newHP);
|
|
//entity.Set<int>("HP", newHP);
|
|
foreach (var x in entity.GetCallbacks<IHealthCallback>())
|
|
{
|
|
x.OnSetHP(newHP);
|
|
}
|
|
}
|
|
void OnSetAlive(bool alive)
|
|
{
|
|
foreach (var x in entity.GetCallbacks<IHealthCallback>())
|
|
{
|
|
x.OnSetAlive(alive);
|
|
}
|
|
//entity.Invoke<bool>(_onSetAlive, alive);
|
|
//entity.Set<bool>(_isAlive, alive);
|
|
onSetAlive.Invoke(alive);
|
|
}
|
|
void AddHP(int hp)
|
|
{
|
|
OnHealthPointChanged(healthPoint, healthPoint += hp);
|
|
}
|
|
void OnDamage(DamageMessage damageMessage)
|
|
{
|
|
if (damageMessage.target == entity)
|
|
AddHP(-damageMessage.damage);
|
|
}
|
|
#if UNITY_EDITOR
|
|
[BIT]
|
|
public void SetAlive()
|
|
{
|
|
BITAppForUnity.ThrowIfNotPlaying();
|
|
OnHealthPointChanged(-1, 100);
|
|
}
|
|
[BIT]
|
|
public void SetDead()
|
|
{
|
|
BITAppForUnity.ThrowIfNotPlaying();
|
|
OnHealthPointChanged(100, -1);
|
|
}
|
|
#endif
|
|
}
|
|
} |