|
| 1 | +using UnityEngine; |
| 2 | +using UnityEngine.AI; |
| 3 | + |
| 4 | +public class HealthController : MonoBehaviour |
| 5 | +{ |
| 6 | + private static HealthController _instance; |
| 7 | + [SerializeField] public int maxHealth = 100; |
| 8 | + public int CurrentHealth { get; private set; } |
| 9 | + [SerializeField] private HealthUI healthUI; |
| 10 | + [SerializeField] private GameObject haensel; |
| 11 | + [SerializeField] private GameObject gretel; |
| 12 | + [SerializeField] private Transform haenselSpawnPoint; |
| 13 | + [SerializeField] private Transform gretelSpawnPoint; |
| 14 | + private GameObject _passivePlayer; |
| 15 | + private GameOverUIController _gameOverUI; |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | + public static HealthController Instance |
| 20 | + { |
| 21 | + get { |
| 22 | + if (_instance == null) { |
| 23 | + Debug.LogError("Health Controller not instantiated."); |
| 24 | + } |
| 25 | + return _instance; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + private void Start() |
| 30 | + { |
| 31 | + _instance = this; |
| 32 | + CurrentHealth = maxHealth; |
| 33 | + _gameOverUI = GameObject.FindGameObjectWithTag("Canvas").GetComponent<GameOverUIController>(); |
| 34 | + } |
| 35 | + private void Awake() |
| 36 | + { |
| 37 | + _instance = this; |
| 38 | + } |
| 39 | + |
| 40 | + private void Update() |
| 41 | + { |
| 42 | + // calculate index of health sprite image: 10 images from 0-9 in reversed sequence |
| 43 | + healthUI.ChangeHealth(9 - (CurrentHealth / (maxHealth / 10))); |
| 44 | + } |
| 45 | + |
| 46 | + public void TakeDamage(int damage, GameObject player) |
| 47 | + { |
| 48 | + if (CurrentHealth-damage <= 0) |
| 49 | + { |
| 50 | + OnDeath(player); |
| 51 | + return; |
| 52 | + } |
| 53 | + CurrentHealth -= damage; |
| 54 | + player.GetComponent<HealthFlashController>().FlashRed(); |
| 55 | + healthUI.Flash(); |
| 56 | + } |
| 57 | + |
| 58 | + public void Heal(int amount) |
| 59 | + { |
| 60 | + if (CurrentHealth + amount <= maxHealth) |
| 61 | + { |
| 62 | + CurrentHealth += amount; |
| 63 | + } |
| 64 | + else |
| 65 | + { |
| 66 | + CurrentHealth = maxHealth; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public void OnDeath(GameObject player) |
| 71 | + { |
| 72 | + Debug.Log("Game Over"); |
| 73 | + _gameOverUI.ToggleGameOverUI(); |
| 74 | + _passivePlayer = haensel.CompareTag(player.tag) ? gretel : haensel; |
| 75 | + _passivePlayer.GetComponent<NavMeshAgent>().enabled = false; |
| 76 | + haensel.transform.position = haenselSpawnPoint.position; |
| 77 | + gretel.transform.position = gretelSpawnPoint.position; |
| 78 | + _passivePlayer.GetComponent<NavMeshAgent>().enabled = true; |
| 79 | + CurrentHealth = maxHealth; |
| 80 | + } |
| 81 | +} |
0 commit comments