轉(zhuǎn)載自:http.dsqiu.iteye.com
插件的詳解在鏈接里已經(jīng)說的很清楚了,這里主要說下我改了一些代碼讓timer支持時間戳。以及增加了暫停和繼續(xù)的方法。
先說說支持時間戳的部分:
外部接口加了個參數(shù),用于判斷是否需要用時間戳:
// time + callback + [timer handle]
public static void In(float delay, Callback callback, Handle timerHandle = null, bool isConvertDate = false)
{ Schedule(delay, callback, null, null, timerHandle, 1, -1.0f, isConvertDate); }
獲取剩余的時間,用于暫停和繼續(xù)
/// <summary>
/// 讀取本地存儲時間戳,獲取剩余的時間
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static float ContinueStartForConvertDateTime(string key)
{
if (PlayerPrefs.GetString("key") == null)
return -1;
if (PlayerPrefs.GetString(key) != "" && Int64.Parse(PlayerPrefs.GetString(key)) != 0)
{
float time = (Int64.Parse(PlayerPrefs.GetString(key)) - CommonFuntion.ConvertDateTimeForMillise(DateTime.Now)) * 0.001f;
UnityEngine.Debug.Log("----------------"+ time);
if (time < 0)
time = 0;
return time;
}
else
return -1;
}
Schedule添加定時器方法中isConvertDate如果是true,定時器用的就是時間戳,同時存儲在本地數(shù)據(jù)中
if(isConvertDate)
{
pauseTime = 0;
long start = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now);
long end = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now.AddMilliseconds(time * 1000));
m_NewEvent.StartTimeDateTime = start;
m_NewEvent.DueTimeDateTime= end;
PlayerPrefs.SetString(dataKey, end.ToString());
UnityEngine.Debug.Log(CommonFuntion.ConvertDateTime(DateTime.Now) + "---------------"+start + "------------"+ end + "----------"+(end- start)*0.001f+"-----"+time);
}
else
{
m_NewEvent.StartTime = Time.time;
m_NewEvent.DueTime = Time.time + time;
}
m_NewEvent.Iterations = iterations;
m_NewEvent.Interval = interval;
Update中增加判斷時間戳定時器完成條件:
long start = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now);
// execute all due events
if ((Time.time >= vp_Timer.m_Active[m_EventIterator].DueTime && vp_Timer.m_Active[m_EventIterator].DueTime != 0) || // time is up
vp_Timer.m_Active[m_EventIterator].Id == 0 || (start >= vp_Timer.m_Active[m_EventIterator].DueTimeDateTime && vp_Timer.m_Active[m_EventIterator].DueTimeDateTime != 0))// event has been canceled ('Execute' will kill it)
vp_Timer.m_Active[m_EventIterator].Execute();
DueTime數(shù)據(jù)處理的地方也要添加DueTimeDateTime相應(yīng)的處理:
private void Recycle()
{
Id = 0;
DueTime = 0.0f;
//重置時間戳
if(DueTimeDateTime > 0 && pauseTime <= 0)
PlayerPrefs.SetString(dataKey, "");
DueTimeDateTime = 0;
StartTime = 0.0f;
Function = null;
ArgFunction = null;
Arguments = null;
if (vp_Timer.m_Active.Remove(this))
m_Pool.Add(this);
#if (UNITY_EDITOR && DEBUG)
EditorRefresh();
#endif
}
public void Execute()
{
// if either 'Id' or 'DueTime' is zero, this timer has been
// canceled: recycle it!
if (Id == 0 || (DueTime == 0.0f && DueTimeDateTime == 0))
{
Recycle();
return;
}
// attempt to execute the callback function
if (Function != null)
Function();
else if (ArgFunction != null)
ArgFunction(Arguments);
else
{
// function was null: nothing to do so abort
Error("Aborted event because function is null.");
Recycle();
return;
}
// count down to recycling
if (Iterations > 0)
{
Iterations--;
// usually a timer has one default iteration and will
// enter the below scope to get recycled right away ...
if (Iterations < 1)
{
Recycle();
return;
}
}
// ... but if we end up here the timer either has atleast one
// iteration left, or user set iterations to zero for infinite
// repetition. either way: update due time with the interval
DueTime = Time.time + Interval;
DueTimeDateTime = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now.AddMilliseconds(Interval * 1000));
}
在SchedulingDemo場景中進行測試
SchedulingDemo腳本中我的測試代碼:
void Start()
{
float time = vp_Timer.ContinueStartForConvertDateTime(vp_Timer.dataKey);
PlayerPrefs.SetString(vp_Timer.dataKey, "");
if (time >= 0)
{
StartCoroutine(Test(time));
}
}
IEnumerator Test(float time)
{
yield return new WaitForEndOfFrame();
callback = SmackCube;
vp_Timer.In(time, callback, 5, 0.5f, null, true);
}
...
...
if (DoButton("----10秒后執(zhí)行----5 iterations of a method, with 0.5 sec intervals"))
{
callback = SmackCube;
vp_Timer.In(10f, SmackCube, 5, 0.5f, null, true);
}
...
...
運行后
![~GSDIM9XE0NNQ8U1]W5S111.png](http://upload-images.jianshu.io/upload_images/1239783-9b5515db781b1675.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
關(guān)閉后重新運行,實現(xiàn)重新進游戲繼續(xù)計時。

可以看出時間戳數(shù)據(jù)我用的都是精確到毫秒的,因為在Update中有獲取數(shù)據(jù),如果只是精確到秒的話,一下就被判定是完成了。
timer沒有封裝暫停和繼續(xù)的方法,但是事件的數(shù)據(jù)都有封裝在Event里,所以加個暫停和繼續(xù)自然是no problem。。。于是馬上動手給他加了一個暫停和繼續(xù)的方法,我的思路是暫停的時候把活躍的Event列表和剩余時間存起來,繼續(xù)的時候再用對應(yīng)的剩余時間去激活,單個事件可以通過MethodName來暫停和繼續(xù):
vp_Timer中新增的暫停接口:
public static void PauseAll(string methodName = "")
{
if (methodName != "")
{
Event e = m_Active.Find((eventItem) => eventItem.MethodName == methodName);
if (e == null)
return;
e.Paused = true;
eventPauseList.Add(e);
//暫停后剩余時間
float residueTime = e.isConvertDate ? ((e.DueTimeDateTime - CommonFuntion.ConvertDateTimeForMillise(DateTime.Now)) * 0.001f) : (e.DueTime - e.StartTime) - e.LifeTime;
UnityEngine.Debug.Log(e.MethodName + "-------Pause-------residueTime : " + residueTime);
pauseTimeList.Add(residueTime);
DestroyAll(methodName);
}
else
{
PauseDataSave();
DestroyAll();
}
}
private static void PauseDataSave()
{
for (int t = 0; t < m_Active.Count; t++)
{
if (m_Active[t].Paused)
continue;
m_Active[t].Paused = true;
eventPauseList.Add(m_Active[t]);
//暫停后剩余時間
float residueTime = m_Active[t].isConvertDate ? ((m_Active[t].DueTimeDateTime - CommonFuntion.ConvertDateTimeForMillise(DateTime.Now)) * 0.001f) : (m_Active[t].DueTime - m_Active[t].StartTime) - m_Active[t].LifeTime;
UnityEngine.Debug.Log(eventPauseList[t].MethodName + "-------PauseAll-------residueTime : " + residueTime);
pauseTimeList.Add(residueTime);
}
}
public static void ContiuePlayAll()
{
for (int t = 0; t < eventPauseList.Count; t++)
{
eventPauseList[t].Paused = false;
Schedule(pauseTimeList[t], eventPauseList[t].Function, eventPauseList[t].ArgFunction, eventPauseList[t].Arguments, null, eventPauseList[t].Iterations, eventPauseList[t].Interval, eventPauseList[t].isConvertDate);
UnityEngine.Debug.Log(eventPauseList[t].MethodName + "-------ContiuePlayAll-------pauseTimeList[t] : " + pauseTimeList[t]);
}
eventPauseList.Clear();
pauseTimeList.Clear();
}
SchedulingDemo腳本中我的測試代碼:
if (GUI.Button(new Rect(Screen.width * 0.85f, Screen.width * 0.2f + Screen.width * 0.05f, Screen.width * 0.04f * 3, Screen.width * 0.04f), "Pause"))
{
if (callback != null)
vp_Timer.PauseAll(callback.Method.Name);
}
if (GUI.Button(new Rect(Screen.width * 0.85f, Screen.width * 0.25f + Screen.width * 0.05f, Screen.width * 0.04f * 3, Screen.width * 0.04f), "PauseAll"))
{
vp_Timer.PauseAll();
}
if (GUI.Button(new Rect(Screen.width * 0.85f, Screen.width * 0.3f + Screen.width * 0.05f, Screen.width * 0.04f * 3, Screen.width * 0.04f), "PlayAll"))
{
vp_Timer.ContiuePlayAll();
}
測試結(jié)果:

對時間戳定時的因為我有存本地數(shù)據(jù),所以暫停和繼續(xù)只有在運行中有生效。
如果要實現(xiàn)某一個事件在延時幾秒后調(diào)幾次,間隔多少時間這種比較復(fù)雜的流程只要1句簡短的代碼就能搞定,想想是不是還有點小激動呢。
if (DoButton("----10秒后執(zhí)行----5 次調(diào)用, 間隔 0.5 秒"))
{
callback = SmackCube;
vp_Timer.In(10f, SmackCube, 5, 0.5f, null, true);
}
這個插件還有做用字符串來標記delegate

今天的內(nèi)容就到這啦,研究完是不是覺得VisionTimer還蠻給力的呢。