-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgressBar.cs
112 lines (98 loc) · 2.97 KB
/
ProgressBar.cs
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class ProgressBar : MonoBehaviour
{
[Header("Title Setting")]
public string Title;
public Color TitleColor;
public Font TitleFont;
public int TitleFontSize = 10;
[Header("Bar Setting")]
public Color BarColor;
public Color BarBackGroundColor;
public Sprite BarBackGroundSprite;
[Range(1f, 100f)]
public int Alert = 20;
public Color BarAlertColor;
[Header("Sound Alert")]
public AudioClip sound;
public bool repeat = false;
public float RepeatRate = 1f;
private Image bar, barBackground;
private float nextPlay;
private AudioSource audiosource;
private Text txtTitle;
private float barValue;
public float BarValue
{
get { return barValue; }
set
{
value = Mathf.Clamp(value, 0, 100);
barValue = value;
UpdateValue(barValue);
}
}
private void Awake()
{
bar = transform.Find("Bar").GetComponent<Image>();
barBackground = GetComponent<Image>();
txtTitle = transform.Find("Text").GetComponent<Text>();
barBackground = transform.Find("BarBackground").GetComponent<Image>();
audiosource = GetComponent<AudioSource>();
}
private void Start()
{
txtTitle.text = Title;
txtTitle.color = TitleColor;
txtTitle.font = TitleFont;
txtTitle.fontSize = TitleFontSize;
bar.color = BarColor;
barBackground.color = BarBackGroundColor;
barBackground.sprite = BarBackGroundSprite;
// Initialize the bar value to full health
BarValue = 100;
}
void UpdateValue(float val)
{
bar.fillAmount = val / 100;
txtTitle.text = Title + " " + val.ToString("F0") + "%"; // F0 for no decimal places
if (Alert >= val)
{
bar.color = BarAlertColor;
}
else
{
bar.color = BarColor;
}
}
private void Update()
{
if (!Application.isPlaying)
{
UpdateValue(50); // For editor preview
txtTitle.color = TitleColor;
txtTitle.font = TitleFont;
txtTitle.fontSize = TitleFontSize;
bar.color = BarColor;
barBackground.color = BarBackGroundColor;
barBackground.sprite = BarBackGroundSprite;
}
else
{
if (Alert >= barValue && Time.time > nextPlay)
{
nextPlay = Time.time + RepeatRate;
audiosource.PlayOneShot(sound);
}
}
}
// Call this method from the PlayerScript when the player takes damage
public void UpdateHealth(float currentHealth, float maxHealth)
{
BarValue = (currentHealth / maxHealth) * 100;
}
}