本文永久地址:http://www.omuying.com/article/124.aspx,
【文章转载请注明出处!】
在平时的开发过程中,计时、倒计时经常在游戏中用到,想必大家都有自己的处理高招,为了以后用方便使用,抽象出一个 TimerManager 类,功能很简单,这儿采用协程的 WaitForSeconds 来处理计时、倒计时,希望对你有所帮助!
主要代码如下:
003 | using System.Collections; |
004 | using System.Collections.Generic; |
006 | public class TimerManager |
008 | private static Dictionary< string , TimerItem> dictList = new Dictionary< string , TimerItem>(); |
013 | /// <param name="timerKey">Timer key.</param> |
014 | /// <param name="totalNum">Total number.</param> |
015 | /// <param name="delayTime">Delay time.</param> |
016 | /// <param name="callback">Callback.</param> |
017 | /// <param name="endCallback">End callback.</param> |
018 | public static void Register( string timerKey, int totalNum, float delayTime, Action< int > callback, Action endCallback) |
020 | TimerItem timerItem = null ; |
021 | if (!dictList.ContainsKey(timerKey)) |
023 | GameObject objectItem = new GameObject (); |
024 | objectItem.name = timerKey; |
026 | timerItem = objectItem.AddComponent<TimerItem> (); |
027 | dictList.Add(timerKey, timerItem); |
030 | timerItem = dictList[timerKey]; |
033 | if (timerItem != null ) |
035 | timerItem.Run(totalNum, delayTime, callback, endCallback); |
042 | /// <param name="timerKey">Timer key.</param> |
043 | public static void UnRegister( string timerKey) |
045 | if (!dictList.ContainsKey(timerKey)) return ; |
047 | TimerItem timerItem = dictList [timerKey]; |
048 | if (timerItem != null ) |
051 | GameObject.Destroy(timerItem.gameObject); |
056 | class TimerItem : MonoBehaviour |
058 | private int totalNum; |
059 | private float delayTime; |
060 | private Action< int > callback; |
061 | private Action endCallback; |
063 | private int currentIndex; |
065 | public void Run( int totalNum, float delayTime, Action< int > callback, Action endCallback) |
069 | this .currentIndex = 0; |
071 | this .totalNum = totalNum; |
072 | this .delayTime = delayTime; |
073 | this .callback = callback; |
074 | this .endCallback = endCallback; |
076 | this .StartCoroutine ( "EnumeratorAction" ); |
081 | this .StopCoroutine ( "EnumeratorAction" ); |
084 | private IEnumerator EnumeratorAction() |
086 | yield return new WaitForSeconds ( this .delayTime); |
088 | this .currentIndex ++; |
089 | if ( this .callback != null ) this .callback( this .currentIndex); |
091 | if ( this .totalNum != -1) |
093 | if ( this .currentIndex >= this .totalNum) |
095 | if ( this .endCallback != null ) this .endCallback(); |
099 | this .StartCoroutine( "EnumeratorAction" ); |