-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleTimer.cs
More file actions
74 lines (62 loc) · 1.81 KB
/
SimpleTimer.cs
File metadata and controls
74 lines (62 loc) · 1.81 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
using System;
using System.Collections;
using SubsurfaceStudios.Attributes;
using SubsurfaceStudios.Utilities.Async;
using UnityEngine;
using UnityEngine.Events;
namespace SubsurfaceStudios.Utilities.Timers
{
[Serializable]
public class SimpleTimer
{
public float duration;
[Header("Runtime")]
[InspectorReadOnly] public bool isRunning = false;
[InspectorReadOnly] public float currentTime = 0f;
public UnityEvent<float> onTimerStart;
public UnityEvent<float> onTimerTick;
public UnityEvent<float> onTimerStop;
public SimpleTimer(float duration)
{
this.duration = duration;
}
public void Start()
{
if (isRunning)
{
Debug.LogError("Timer already running!");
return;
}
isRunning = true;
Execute(onTimerStart, currentTime);
StaticCoroutineHandler.StartCoroutineStatic(Timer());
}
private void Execute(UnityEvent<float> action, float value) {
try {
action?.Invoke(value);
} catch (Exception ex) {
Debug.LogException(ex);
}
}
public IEnumerator Timer()
{
while (currentTime < duration && isRunning)
{
currentTime += Time.deltaTime;
Execute(onTimerTick, currentTime);
yield return null;
}
isRunning = false;
Execute(onTimerStop, currentTime);
}
public void Reset()
{
currentTime = 0f;
}
public void Stop()
{
isRunning = false;
Execute(onTimerStop, currentTime);
}
}
}