原地址:http://blog.sina.com.cn/s/blog_5b6cb9500101aejs.html
https://github.com/xuzhiping7/Unity3d-Timer
项目中管理计时器太混乱难看了,用好听点的话来说就是代码不优雅。
想了下就随手简单写了个时间管理模块了。其实有好几种实现方式的,但是选用了U3D最为合适和简单的方式写。效率可能不高,但做小游戏是压根没问题的了。
原理简单点来说就是统一管理计时器。
每个计时器有自己的开始、暂停、结束、重新开始。当计时结束之后则调用相应的一个或者多个函数。
Timer.cs算是基类,TimerManager.cs则是管理每一个计时器的管理程序。根据不同的项目改至适用即可。
就那样,代码非常简单。就是一个委托回调。
具体代码放到GITHUB了,有兴趣的同学可以上去看看。
https://github.com/xuzhiping7/Unity3d-Timer
//Coded by ZhipingXu xuzhiping7@qq.com //Too simple, so I do not need to explain, just see the code. Help yourself.public class Timer{ //If the Timer is running private bool b_Tricking; //Current time private float f_CurTime; //Time to reach private float f_TriggerTime; //Use delegate to hold the methods public delegate void EventHandler(); //The trigger event list public event EventHandler tick; ////// Init /// /// Trigger Time public Timer(float second) { f_CurTime = 0.0f; f_TriggerTime = second; } ////// Start Timer /// public void Start() { b_Tricking = true; } ////// Update Time /// public void Update(float deltaTime) { if (b_Tricking) { f_CurTime += deltaTime; if (f_CurTime > f_TriggerTime) { //b_Tricking must set false before tick() , cause if u want to restart in the tick() , b_Tricking would be reset to fasle . b_Tricking = false; tick(); } } } ////// Stop the Timer /// public void Stop() { b_Tricking = false; } ////// Continue the Timer /// public void Continue() { b_Tricking = true; } ////// Restart the this Timer /// public void Restart() { b_Tricking = true; f_CurTime = 0.0f; } ////// Change the trigger time in runtime /// /// Trigger Time public void ResetTriggerTime(float second) { f_TriggerTime = second; }}
using UnityEngine;using System.Collections;public class TimerManager : MonoBehaviour{ Timer test; // Use this for initialization void Start () { test = new Timer(3.0f); test.tick += Test; test.tick += Test2; test.Start(); } // Update is called once per frame void Update () { //If u have many timer //u also can serval frame call one time to save some performance, but the deltaTime u should calculate youself //like :(u should define lastTime youself-- float) /* if(Time.frameCount%5 == 0) { delta = Time.time - lastTime; test.Update(Time.deltaTime); lastTime = Time.time; } */ test.Update(Time.deltaTime); } //Some time u may need this to avoid conflict when re-init something , just a tip . void OnDestory(){ test.tick -= Test; test.tick -= Test2; } void Test() { Debug.Log("1"); } void Test2() { Debug.Log("2"); }}