VisionTimer定時器插件

轉(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ù)計時。

SQ_DD)H_005%2HWXT2(D$13.png

可以看出時間戳數(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é)果:


Paste_Image.png

對時間戳定時的因為我有存本地數(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


Paste_Image.png

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,608評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,139評論 25 708
  • (噴火龍今天回憶下身邊朋友,說說他們怎么做生鮮電商?。?01 2013年,我認識福哥,那時他候投資了一個校園團隊,...
    二秋生活閱讀 423評論 0 0
  • 文|初夏 天蒙蒙亮,周圍一片寂靜,突然“喵”的一聲貓叫響起,我輕輕扭頭,看到一只黑貓在我們斜后方不遠處蹲著,對,是...
    2017初夏閱讀 327評論 2 2
  • 我的夢都很稀奇古怪。我覺得自己本身就是個怪女孩,腦袋里總是想一些奇奇怪怪的不找邊際的,甚至不該想的東西。 剛放暑假...
    王小Qian閱讀 403評論 0 0

友情鏈接更多精彩內(nèi)容