This repository has been archived by the owner on Nov 18, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Timer.cs
114 lines (99 loc) · 3.19 KB
/
Timer.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
113
114
using System;
using UnityEngine;
namespace Oxide
{
/// <summary>
/// Represents a timer that fires a callback after a specific delay
/// </summary>
public class Timer
{
/// <summary>
/// The number of iterations remaining on this timer
/// </summary>
public int IterationsRemaining { get; private set; }
/// <summary>
/// The delay between each iteration in seconds
/// </summary>
public float Delay { get; private set; }
/// <summary>
/// The callback to raise upon each iteration
/// </summary>
public Action Callback { get; private set; }
private float createtime, nextiteration;
private bool isfinished;
/// <summary>
/// Raised when the timer finishes
/// </summary>
public event Action<Timer> OnFinished;
private Timer(int iterations, float delay)
{
// Store parameters
IterationsRemaining = iterations;
Delay = delay;
// Store needed timestamps
createtime = Time.realtimeSinceStartup;
nextiteration = createtime + Delay;
}
/// <summary>
/// Updates this timer
/// </summary>
public void Update()
{
// Sanity check
if (isfinished) return;
// Is it time to fire an iteration off?
float time = Time.realtimeSinceStartup;
if (time >= nextiteration)
{
// Calculate next iteration
nextiteration = time + Delay;
if (IterationsRemaining > 0)
{
IterationsRemaining--;
if (IterationsRemaining == 0) Destroy();
}
// Raise callback
//Debug.Log("Timer firing");
Callback();
}
}
/// <summary>
/// Finishes this timer
/// </summary>
public void Destroy()
{
// Sanity check
if (isfinished) return;
// We're done
isfinished = true;
if (OnFinished != null) OnFinished(this);
}
#region Static Interface
/// <summary>
/// Creates a time that will fire for a fixed number of iterations and then finish
/// </summary>
/// <param name="delay"></param>
/// <param name="numiterations"></param>
/// <param name="callback"></param>
/// <returns></returns>
public static Timer Create(float delay, int numiterations, Action callback)
{
Timer result = new Timer(numiterations, delay);
result.Callback = callback;
return result;
}
/// <summary>
/// Create a timer that will fire indefinetely
/// </summary>
/// <param name="delay"></param>
/// <param name="callback"></param>
/// <returns></returns>
public static Timer Create(float delay, Action callback)
{
Timer result = new Timer(0, delay);
result.Callback = callback;
return result;
}
#endregion
}
}