I’m assuming this lecture discussed and overcame floating point imprecision for the sake of teaching it, because this solution to me was unnecessarily complex for such a simple issue.
Some of my code is different from Sam’s but basically have bool that is changed and based on whether the character is alive or not:
bool _isDead = false;
public bool IsDead => _isDead;
Then in the healthbar.cs you can use:
if (_health.IsDead)
{
gameObject.SetActive(false);
}
You can also follow a long my alternative of using an event instead of unity event when taking damage:
And then update the healthbar based on the event:
public class HealthBar : MonoBehaviour
{
[SerializeField] Health _health = null;
[SerializeField] RectTransform _healthBarForeground = null;
const int _turnPercentageIntoFraction = 100;
private void OnEnable()
{
_health.OnTakeDamage += UpdateHealthBar;
}
private void Start()
{
ScaleHealthBarBasedOnHP();
}
void UpdateHealthBar(float damage)
{
ScaleHealthBarBasedOnHP();
}
private void ScaleHealthBarBasedOnHP()
{
_healthBarForeground.localScale = new Vector3(
_health.CurrentPercentageFromMax() / _turnPercentageIntoFraction, 1, 1);
if (_health.IsDead)
{
gameObject.SetActive(false);
}
}
private void OnDisable()
{
_health.OnTakeDamage -= UpdateHealthBar;
}
}