-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHealthUI.cs
More file actions
88 lines (79 loc) · 2.7 KB
/
HealthUI.cs
File metadata and controls
88 lines (79 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class HealthUI: MonoBehaviour {
Image heartComponent;
static Sprite fullHeart;
static Sprite emptyHeart;
[SerializeField] EntityType entityType;
List<Image> hearts;
int lastHeart;
CanvasGroup canvasGroup;
void Awake() {
heartComponent = GetComponentInChildren<Image>();
if (heartComponent == null) {
Debug.LogError("HealthUI is missing default heart Image component.");
}
if (fullHeart == null) {
fullHeart = Resources.Load<Sprite>("Heart-full");
if (fullHeart == null) {
Debug.LogError("Could not load Full Heart image.");
}
}
if (emptyHeart == null) {
emptyHeart = Resources.Load<Sprite>("Heart-empty");
if (emptyHeart == null) {
Debug.LogError("Could not load Empty Heart image.");
}
}
canvasGroup = gameObject.AddComponent<CanvasGroup>();
canvasGroup.blocksRaycasts = false;
canvasGroup.interactable = false;
canvasGroup.alpha = 1f;
}
void Start() {
if (entityType == EntityType.Player) {
Player.I.Health.OnDamage += RemoveHeart;
Player.I.Health.OnDied += FadeOut;
WaveManager.I.OnGameComplete += FadeOut;
InitUI(Player.I.Health.HP);
} else if (entityType == EntityType.Enemy) {
var enemyHealth = GetComponentInParent<Health>();
if (enemyHealth == null) {
Debug.LogError("Could not grab enemy health component.");
}
enemyHealth.OnDamage += RemoveHeart;
enemyHealth.OnDied += FadeOut;
InitUI(enemyHealth.HP);
}
}
void Update() {
if (entityType == EntityType.Enemy) {
transform.FaceCamera();
}
}
void InitUI(int health) {
hearts = new() { heartComponent };
var size = heartComponent.rectTransform.sizeDelta;
//One child already exists.
for (int i = 0; i < health - 1; i++) {
var newChild = Instantiate(heartComponent, transform);
newChild.transform.SetParent(transform);
hearts.Add(newChild);
}
lastHeart = hearts.Count - 1;
}
void RemoveHeart() {
if (lastHeart < 0) {
Debug.LogError("trying to remove heart ui when no hearts are left!");
return;
}
hearts[lastHeart].sprite = emptyHeart;
lastHeart--;
}
void FadeOut() {
new Timeout(() => canvasGroup.DOFade(0f, 0.3f).SetEase(Ease.InOutSine), 0.3f, this);
}
}