Unity时钟定时器插件——Vision Timer源码分析之一

发表于2016-01-27
评论0 2.1k浏览



尊重他人的劳动,支持原创,转载请注明出处:http.dsqiu.iteye.com

 

       因为项目中,UI的所有模块都没有MonBehaviour类(纯粹的C#类),只有像NGUI的基本组件的类是继承MonoBehaviour。因为没有继承MonoBehaviour,这也不能使用Update,InVoke,StartCoroutine等方法,这样就会显得很蹩脚。后来一个同事添加vp_Timer和vp_TimeUtility这两个类。后来研究了下vp_Timer至少可以弥补没有Update,InVoke,InVokeRepeat的不足。

       之前用的时候,就粗略的研究过vp_Timer这个类,一直就想仔细剖析下,但是由于不仅工作任务中,自己也有很多要琐碎的事情,我都很久自己好好学习了,虽然还有一堆事情要做,但是憋了太久了,先满足下自己,所以才有开始认真分析vp_Timer的代码并才有这篇博客。

       

       vp_Timer 一共有3个class,都各司其职:vp_Timer,Event,Handle

                 1)vp_Timer:提供的使用接口,通过静态方法vp_Timer.In(),加入定时器事件(函数,这里将传入的函数称为事件)

                 2)Event:用来封装传入的事件(函数),保持事件的状态

                 3)Handle:对事件状态提供查询接口(事件执行了多长时间,结束时间,是否还是Active)以及提供 Excute(立即执行事件),Cancel(取消事件),Pause(暂停事件)等操作

       很容易就可以理清这三者的关系,通过vp_Timer.In方法将传入的事件(函数)封装为Event对象,然后返回(虽然是通过参数)Handle对象让调用者可以查询事件的状态和进行相关操作。

       

vp_Timer:

       先看下vp_Timer的成员变量(c#应该称为filed)

GameObject m_MainObject:vp_Timer是一个MonoBehaviour,就一定要挂载GameObject上,m_MainObject会在第一次调用vp_Timer.In方法时创建:

C#代码  
  1. // setup main gameobject  
  2. if (m_MainObject == null)  
  3. {  
  4.     m_MainObject = new GameObject("Timers");  
  5.     m_MainObject.AddComponent<vp_Timer>();  
  6.     UnityEngine.Object.DontDestroyOnLoad(m_MainObject);  
  7.  
  8. #if (UNITY_EDITOR && !DEBUG)  
  9.     m_MainObject.gameObject.hideFlags = HideFlags.HideInHierarchy;  
  10. #endif  
  11. }  

 

 

 List<Event> m_Active 和 List<Event> m_Pool :这个List都是Event的缓存,其中,m_Active缓存Active的Event,m_Pool缓存无效的Event,这里的Acitive是事件仍然需要执行,无效说明不会再被调用。之所有要缓存无效的Event,是为了节省创建Event对象的消耗。m_Pool就好比垃圾箱,m_Active是一个成品工厂,每次m_Active要生产(Add)新的Event,都去m_Pool取没用的原料(Event),当m_Active的成品没用了,用放会m_Pool中去,这样就达到了循环利用作用。

 

 Event m_NewEvent :在Schedule方法里使用的变量,其实完全可以声明为Schedule的局部变量,为了节省重复创建和销毁的消耗,vp_Timer就声明一个成员变量。

private static int m_EventCount = 0;

 

// variables for the Update method

int m_EventBatch 和int m_EventIterator:在Update使用的变量,m_EventBatch记录在一次Update中执行事件的次数,m_EventIterator记录是每次执行事件在m_Active的索引。

 

int MaxEventsPerFrame :一次循环(Update)执行事件最大次数

 

       假设MaxEventPerFarme = 10 , m_Active.Count = 5,那么每次Update都会遍历2次m_Active的Event,看是否可以执行(调用Excute函数)。这样就可以理解这三个参数的具体含义了。

 

Event:

 

C#代码  
  1.     private class Event  
  2.     {  
  3.   
  4.         public int Id;   //标记Event,如果Id = 0 ,表示该Event已经无效,就被Add进m_Pool中,Handle对象和Evnt就是通过Id来关联的  
  5.   
  6.         public Callback Function = null;   //函数委托 Callback和ArgCallback是vp.Timer定义的函数委托(原型)  
  7.         public ArgCallback ArgFunction = null;  
  8.         public object Arguments = null;  
  9.   
  10.         public int Iterations = 1;   //事件的迭代(执行次数)  
  11.         public float Interval = -1.0f;   //执行时间间隔  
  12.         public float DueTime = 0.0f;    //下一个事件执行的时间 DueTime = Time.time + Time.deltaTime  
  13.         public float StartTime = 0.0f;   //事件开始执行事件 StartTime = Time.Time + delayTime  
  14.         public float LifeTime = 0.0f;   //事件累积的总时间 LifeTime += Time.deltaTime  
  15.         public bool Paused = false;  
  16.  
  17. #if (DEBUG && UNITY_EDITOR)  
  18.         private string m_CallingMethod = "";  
  19. #endif  
  20.                //省略其他代码  
  21.        }  

 

 

当然还有几个方法:

       Excute():执行Function和ArgFunction

       Recyle():

C#代码  
  1. private void Recycle()  
  2. {  
  3.   
  4.     Id = 0;  
  5.     DueTime = 0.0f;  
  6.     StartTime = 0.0f;  
  7.   
  8.     Function = null;  
  9.     ArgFunction = null;  
  10.     Arguments = null;  
  11.   
  12.     if (vp_Timer.m_Active.Remove(this))  //从m_Active进入m_Pool  
  13.         m_Pool.Add(this);  
  14.  
  15. #if (UNITY_EDITOR && DEBUG)  
  16.     EditorRefresh();  
  17. #endif  
  18.   
  19. }  

         MethodName:由于D.S.Qiu对delegate还没有深入研究理解,目前还说不清如何比较两个委托是否相等,但是得到一个经验就是不能用 函数 来比较,所以看到很多插件(最典型的就是Unity的StopCoroutine只有字符串作为参数和NGUI的EventDelegate)都使用的字符串来标记delegate,看下面的代码:

C#代码  
  1. public string MethodName  
  2. {  
  3.     get  
  4.     {  
  5.         if (Function != null)  
  6.         {  
  7.             if (Function.Method != null)  
  8.             {  
  9.                 if (Function.Method.Name[0] == '<')  
  10.                     return "delegate";  
  11.                 else return Function.Method.Name;  
  12.             }  
  13.         }  
  14.         else if (ArgFunction != null)  
  15.         {  
  16.             if (ArgFunction.Method != null)  
  17.             {  
  18.                 if (ArgFunction.Method.Name[0] == '<')  
  19.                     return "delegate";  
  20.                 else return ArgFunction.Method.Name;  
  21.             }  
  22.         }  
  23.         return null;  
  24.     }  
  25. }  

 这样vp_Timer才有Cancel(string methodName)的方法:

C#代码  
  1. public static void CancelAll(string methodName)  
  2. {  
  3.     for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)  
  4.     {  
  5.         if (vp_Timer.m_Active[t].MethodName == methodName)  
  6.             vp_Timer.m_Active[t].Id = 0;  
  7.     }  
  8. }  

 

Handle:

        前面介绍过,Handle是用来查询和操作Event的对象,Handle对象和Event桶Id关联起来。

C#代码  
  1. public int Id  
  2. {  
  3.     get  
  4.     {  
  5.         return m_Id;  
  6.     }  
  7.     set  
  8.     {  
  9.         m_Id = value;  
  10.   
  11.         if (m_Id == 0)  
  12.         {  
  13.             m_Event.DueTime = 0.0f;  
  14.             return;  
  15.         }  
  16.   
  17.         m_Event = null;  
  18.         for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)  
  19.         {  
  20.             if (vp_Timer.m_Active[t].Id == m_Id)  
  21.             {  
  22.                 m_Event = vp_Timer.m_Active[t];  
  23.                 break;  
  24.             }  
  25.         }  
  26.         if (m_Event == null)  
  27.             UnityEngine.Debug.LogError("Error: (vp_Timer.Handle) Failed to assign event with Id '" + m_Id + "'.");  
  28.   
  29.         // store some initial event info  
  30.         m_StartIterations = m_Event.Iterations;  
  31.         m_FirstDueTime = m_Event.DueTime;  
  32.   
  33.     }  
  34. }  

 

 还说vp_Timer

        前面介绍了vp_Timer的成员变量以及Event和Handle,就差vp_Timer的使用了,通过调用vp_Timer.In函数将事件加入vp_Timer的mActive队列:

C#代码  
  1. // time + callback + [timer handle]  
  2.     public static void In(float delay, Callback callback, Handle timerHandle = null)  
  3.     { Schedule(delay, callback, nullnull, timerHandle, 1, -1.0f); }  
  4.   
  5.     // time + callback + iterations + [timer handle]  
  6.     public static void In(float delay, Callback callback, int iterations, Handle timerHandle = null)  
  7.     { Schedule(delay, callback, nullnull, timerHandle, iterations, -1.0f); }  
  8.   
  9.     // time + callback + iterations + interval + [timer handle]  
  10.     public static void In(float delay, Callback callback, int iterations, float interval, Handle timerHandle = null)  
  11.     { Schedule(delay, callback, nullnull, timerHandle, iterations, interval); }  
  12.   
  13.     // time + callback + arguments + [timer handle]  
  14.     public static void In(float delay, ArgCallback callback, object arguments, Handle timerHandle = null)  
  15.     { Schedule(delay, null, callback, arguments, timerHandle, 1, -1.0f); }  
  16.   
  17.     // time + callback + arguments + iterations + [timer handle]  
  18.     public static void In(float delay, ArgCallback callback, object arguments, int iterations, Handle timerHandle = null)  
  19.     { Schedule(delay, null, callback, arguments, timerHandle, iterations, -1.0f); }  
  20.   
  21.     // time + callback + arguments + iterations + interval + [timer handle]  
  22.     public static void In(float delay, ArgCallback callback, object arguments, int iterations, float interval, Handle timerHandle = null)  
  23.     { Schedule(delay, null, callback, arguments, timerHandle, iterations, interval); }  

 看到都是对Schedule的封装:

C#代码  
  1. private static void Schedule(float time, Callback func, ArgCallback argFunc, object args, Handle timerHandle, int iterations, float interval)  
  2. {  
  3. if (func == null && argFunc == null)  
  4. {  
  5.     UnityEngine.Debug.LogError("Error: (vp_Timer) Aborted event because function is null.");  
  6.     return;  
  7. }  
  8. // setup main gameobject  
  9. if (m_MainObject == null)  //new 一个 m_MainObject,挂载vp_Timer_  
  10. {  
  11.     m_MainObject = new GameObject("Timers");  
  12.     m_MainObject.AddComponent<vp_Timer>();  
  13.     UnityEngine.Object.DontDestroyOnLoad(m_MainObject);  
  14.  
  15. #if (UNITY_EDITOR && !DEBUG)  
  16.         m_MainObject.gameObject.hideFlags = HideFlags.HideInHierarchy;  
  17. #endif  
  18. }  
  19.   
  20. // force healthy time values  
  21. time = Mathf.Max(0.0f, time);  
  22. iterations = Mathf.Max(0, iterations);  
  23. interval = (interval == -1.0f) ? time : Mathf.Max(0.0f, interval);  
  24.   
  25. // recycle an event - or create a new one if the pool is empty:先从m_Pool中去Event,如果m_Pool为空则直接new一个  
  26. m_NewEvent = null;  
  27. if (m_Pool.Count > 0)     
  28. {   
  29.     m_NewEvent = m_Pool[0];  
  30.     m_Pool.Remove(m_NewEvent);  
  31. }  
  32. else  
  33.     m_NewEvent = new Event();  
  34.   
  35. // iterate the event counter and store the id for this event  
  36. vp_Timer.m_EventCount++;  
  37. m_NewEvent.Id = vp_Timer.m_EventCount;   //Event的Id为当前队列的总数  
  38.   
  39. // set up the event with its function, arguments and times  
  40. if (func != null)  
  41.     m_NewEvent.Function = func;  
  42. else if (argFunc != null)  
  43. {  
  44.     m_NewEvent.ArgFunction = argFunc;  
  45.     m_NewEvent.Arguments = args;  
  46. }  
  47. m_NewEvent.StartTime = Time.time;  //设置Event的成员变量  
  48. m_NewEvent.DueTime = Time.time + time;  
  49. m_NewEvent.Iterations = iterations;  
  50. m_NewEvent.Interval = interval;  
  51. m_NewEvent.LifeTime = 0.0f;  
  52. m_NewEvent.Paused = false;  
  53.   
  54. // add event to the Active list  
  55. vp_Timer.m_Active.Add(m_NewEvent);  
  56.   
  57. // if a timer handle was provided, associate it to this event,  
  58. // but first cancel any already active event using the same  
  59. // handle: there can be only one ...  
  60. if (timerHandle != null)  
  61. {  
  62.     if (timerHandle.Active)  
  63.         timerHandle.Cancel();  
  64.     // setting the 'Id' property associates this handle with  
  65.     // the currently active event with the corresponding id  
  66.     timerHandle.Id = m_NewEvent.Id;   //关联Handle和Event,然后Handle就可以通过关联的Event查询其状态和操作  
  67. }  

 Update:通过比对Time.time和Event.DueTime,如果Time.time >= Event.DueTime 则执行Event的Excute方法。

C#代码  
  1. private void Update()  
  2. {  
  3.   
  4.     //  NOTE: this method never processes more than 'MaxEventsPerFrame',  
  5.     // in order to avoid performance problems with excessive amounts of  
  6.     // timers. this may lead to events being delayed a few frames.  
  7.     // if experiencing delayed events 1) try to cut back on the amount  
  8.     // of timers created simultaneously, and 2) increase 'MaxEventsPerFrame'  
  9.   
  10.     // execute any active events that are due, but only check  
  11.     // up to max events per frame for performance  
  12.     m_EventBatch = 0;  
  13.     while ((vp_Timer.m_Active.Count > 0) && m_EventBatch < MaxEventsPerFrame)  
  14.     {  
  15.   
  16.         // if we reached beginning of list, halt until next frame  
  17.         if (m_EventIterator < 0)  
  18.         {  
  19.             // this has two purposes: 1) preventing multiple iterations  
  20.             // per frame if our event count is below the maximum, and  
  21.             // 2) preventing reaching index -1  
  22.             m_EventIterator = vp_Timer.m_Active.Count - 1;  
  23.             break;  
  24.         }  
  25.   
  26.         // prevent index out of bounds  
  27.         if (m_EventIterator > vp_Timer.m_Active.Count - 1)  
  28.             m_EventIterator = vp_Timer.m_Active.Count - 1;  
  29.   
  30.         // execute all due events  
  31.         if (Time.time >= vp_Timer.m_Active[m_EventIterator].DueTime ||   // time is up  
  32.             vp_Timer.m_Active[m_EventIterator].Id == 0)                 // event has been canceled ('Execute' will kill it)  
  33.             vp_Timer.m_Active[m_EventIterator].Execute();  
  34.         else  
  35.         {  
  36.             // handle pausing  
  37.             if (vp_Timer.m_Active[m_EventIterator].Paused)  
  38.                 vp_Timer.m_Active[m_EventIterator].DueTime += Time.deltaTime;  
  39.             else  
  40.                 // log lifetime  
  41.                 vp_Timer.m_Active[m_EventIterator].LifeTime += Time.deltaTime;  
  42.         }  
  43.   
  44.         // going backwards since 'Execute' will remove items from the list  
  45.         m_EventIterator--;  
  46.         m_EventBatch++;  
  47.     }  
  48.   
  49. }  

 

        差不多就这样了,很久没写博客了,感觉一点也不顺畅,虽然理解的很透彻,还是很为自己的写作功底捉急。

        

小结:

       D.S.Qiu觉得在项目中很有必要有“管理”的思想,很多功能都是用一个类实现的,其他人只要调用就可以了,具体的逻辑只需要在一个类内部维护,可以做的统一控制,可以做到更自如,就拿vp_Timer和MonoBehaviour的InVokeRepeat方法来对比就有明显的优势:

               1)vp_Timer可以随时查询事件的状态(事件被执行了次数等)还可以暂停事件,而InVokeRepeat做不到的

               2)vp_Timer可以设置时间delatTime受不受Time.timeScale影响,而InVokeRepeat是没有这个参数设置的

               3)vp_Timer可以对事件进行统一的管理,如果暂停所有事件的执行,这个点当Time.timeScale = 0 时特别管用,而InVokeRepeat是分散的,没有统一管理其他。

 这有点“一夫当万夫莫开”的感觉。

       不管是InVokeRepeat方法,MonoBehaviour的很多方法都有类似的缺陷,因为每一个MonoBehaviour都可以调用这些方法,就不能统一起来管理了,所以如果Unity当初能写一个专门的类我想会方便很多。

 

       虽然觉得vp_Timer用的很爽,但是D.S.Qiu还是觉得有很多可以改进的地方:

              1)vp_Timer提供Pause(string methodName)和PauseAll()的方法,从“管理”的角度上就更加完美了,当然还有对应的Play方法。

              2)当Event的参数: Iterations 和  Interval 没有很好处理 Interval 和 Time.deltaTime 的具体情况,假设我们的 Iterations =100 , interval = 0.01f  即我需要达到1s内执行100次的目的,但按照vp_Timer的实现结果是执行了100次,但是时间一定是>= 1s,即当Time.deltaTime > interval 时,还是只执行一次,例如 Time.deltaTime = 0.02f, 理论上我们希望能执行两次,但是却只执行了一次。

             3)vp_Timer要是提供 string methodName 到 Event 或 Handle 的查询接口就更加完美了。

             4)vp_Timer虽然用了很多设计,对象的重复利用避免 new 和销毁对象的系统开销,但是专门用Handle专门管理Event,Handle的的功能只是对Event的一个封装,其实完全没有必要,完全可以让Event自己充当Handle的角色,直接返回Event对象会更直观,只有在回调的时候用参数返回关联的对象,要不然采用直接返回会更明白。

 

       虽然上面的分析文章写得比较零乱,但是小结部分我还是很满意的,至少D.S.Qiu之前从来没有在这部分写那么多,算是分享自己的一些经验和体会吧,也发现自己对delegate的不足,又到1:30了时间真是不够用,4个小时就这么过去了。

 

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引