1,计时器的时间判断,Time.time与Time.realtimeSinceStartup都是运行时从0开始,区别是上加的速度是不是按真实时间来的。
2,到达调用的时间,每个需要调用的函数,在添加时,就取到当时的时间,以此做判断。每次函数被调用时,还需更新到当前时间。为下次做判断。
3,调用的次数,每次调用减一,等于0移除,小于0不做操作,
4,移除计时器,设置任意的一个标记,移除时对计时器列表做一次遍历,有该标记的索引则被移除。
以下是代码:
float tmpTime;
void Update () {
for (int i = 0; i < m_lTimeItem_Mng.Count; i++)
{
TimeItem tmpItem = m_lTimeItem_Mng[i];
tmpTime = Time.time;
if (tmpTime > tmpItem.m_callTime + tmpItem.m_timeGap)
{
1,更新时间
tmpItem.m_callTime = Time.time;
if (tmpItem.m_VoidDelegate != null)
{
tmpItem.m_VoidDelegate();
}
if (tmpItem.m_callNums > 0)
{
tmpItem.m_callNums--;
if (tmpItem.m_callNums == 0)
{
m_lTimeItem_Mng.RemoveAt(i);
}
}
}
}
//都是运行时从0开始,区别是上加的速度,
//tmpTime = Time.time;
//Printf("time",tmpTime);
//tmpTime = Time.realtimeSinceStartup;
//Printf("realTime",tmpTime);
}
List<TimeItem> m_lTimeItem_Mng = new List<TimeItem>();
1,任意的标记
int m_id = 12345;
public class TimeItem {
public int m_itemId;
public int m_timeGap;
public int m_callNums;
public System.Action m_VoidDelegate;
public float m_callTime;
}
public int AddTimeHelp_CB(int timeGap,int callNumas,System.Action CB) {
TimeItem item = new TimeItem();
m_id++;
item.m_itemId = m_id;
item.m_timeGap = timeGap;
item.m_callNums = callNumas;
item.m_VoidDelegate = CB;
item.m_callTime = Time.time;
m_lTimeItem_Mng.Add(item);
return m_id;
}
public void RemoveTimeHelp(int id) {
TimeItem tmpItem;
for (int i = 0; i < m_lTimeItem_Mng.Count; i++)
{
tmpItem = m_lTimeItem_Mng[i];
if (tmpItem.m_itemId == id)
{
m_lTimeItem_Mng.RemoveAt(i);
break;
}
}
}
调用代码如下:
MyTimeHelp m_tmpTimeHelp;
int m_id;
void Start () {
m_tmpTimeHelp = transform.GetComponent<MyTimeHelp>();
m_tmpTimeHelp.AddTimeHelp_CB(2, 2, () => { print("callNum is 2"); });
m_tmpTimeHelp.AddTimeHelp_CB(1, 1, () => { print("callNum is 1"); });
m_id = m_tmpTimeHelp.AddTimeHelp_CB(1, -1, () => { print("callNum is -1"); });
Invoke("TestLoop",6);
}
void TestLoop() {
m_tmpTimeHelp.RemoveTimeHelp(m_id);
}