TimeControl.cs
2.14 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
89
90
91
92
93
94
95
96
97
98
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
public class TimeControl : Singleton<TimeControl>
{
/// <summary>
/// 目标时间
/// </summary>
private float _totalTime;
/// <summary>
/// 当前时间
/// </summary>
private float _curTime;
/// <summary>
/// 回调
/// </summary>
private UnityAction _timeCallBack;
/// <summary>
/// 是否开始计时
/// </summary>
private bool _isStart = false;
/// <summary>
/// 是否时单词计时(计时器只执行一次 或者 按设置的间隔时间执行)
/// </summary>
private bool _isOnce;
void Start()
{
}
void Update()
{
if (_isStart)
{
_curTime += Time.deltaTime;
if (_curTime >= _totalTime)
{
_curTime = 0;
// 如果是单次计时器 此时结束计时器
if (_isOnce)
{
_isStart = false;
}
if (_timeCallBack != null)
{
_timeCallBack.Invoke();
}
}
}
}
/// <summary>
/// 按照指定的时间间隔重复执行回调函数。
/// </summary>
/// <param name="interval"></param>
/// <param name="action"></param>
public void Schedule(float interval, UnityAction action)
{
_totalTime = interval;
_timeCallBack = action;
_isStart = true;
_isOnce = false;
}
/// <summary>
/// 延迟执行回调函数,且只会执行一次。
/// </summary>
/// <param name="interval"></param>
/// <param name="action"></param>
public void ScheduleOnce(float interval, UnityAction action)
{
_totalTime = interval;
_timeCallBack = action;
_isStart = true;
_isOnce = true;
}
/// <summary>
/// 结束所有的计时器
/// </summary>
public void UnSchedule()
{
_isStart = false;
_curTime = 0f;
_totalTime = 0f;
_timeCallBack = null;
}
}