In this project, the Player's Health Script serves as an independent module, managing the player's health logic.
This script enables seamless interaction with other game components and handles all health-related operations.
Additionally, when the player dies, a separate component listens for the OnPlayerDied event, and changes the game state.
public static event Action OnPlayerDamaged;
public static event Action OnPlayerDied;
private void Awake() => playerData.CurrentHealth = playerData.MaxHealth;
public bool IsAlive() => playerData.CurrentHealth > 0;
public int GetCurrentHealth() => playerData.CurrentHealth;
public int GetMaxHealth() => playerData.MaxHealth;
public void TakeDamage()
{
playerData.CurrentHealth -= 1;
if (playerData.CurrentHealth <= 0)
{
Die();
return;
}
OnPlayerDamaged?.Invoke();
}
public void Die()
{
playerData.CurrentHealth = -1;
OnPlayerDied?.Invoke();
Destroy(gameObject);
}
The GameManager oversees the player's death.
Upon death, the game state transitions to "GameOver."
private void OnEnable() => PlayerHealth.OnPlayerDied += OnPlayerDied;
private void OnDisable() => PlayerHealth.OnPlayerDied -= OnPlayerDied;
private void OnPlayerDied() => SetGameState(GameState.GameOver);