unity計時器功能的實現

最近在遊戲開發的過程中需要做一些技能cd, buff持續時間的控制等功能,這些功能都需要一個計時器;

爲了便利開發,自己寫了一個簡單的計時器,這樣大部分有關計時的都可以用此計時器了;

計時器主要實現功能:

在規定的時間內倒計時,其中可以暫停,可以繼續,可以設置是否受時間速率的影響等;

倒計時過程中可以時刻返回倒計時的狀態;

可以獲取倒計時剩餘時間,倒計時結束的回調。

......


以下代碼在unity中測試通過:


計時器代碼

using UnityEngine;
using System.Collections;
using System;

public delegate void CompleteEvent();
public delegate void UpdateEvent(float t);

public class Timer : MonoBehaviour
{
    bool isLog = true;

    UpdateEvent updateEvent ;

    CompleteEvent onCompleted ;
	 
    float timeTarget;   // 計時時間/

    float timeStart;    // 開始計時時間/

    float timeNow;     // 現在時間/

    float offsetTime;   // 計時偏差/

    bool isTimer;       // 是否開始計時/

    bool isDestory = true;     // 計時結束後是否銷燬/

    bool isEnd;         // 計時是否結束/

    bool isIgnoreTimeScale = true;  // 是否忽略時間速率

    bool isRepeate;

    float Time_
    {
        get { return isIgnoreTimeScale ? Time.realtimeSinceStartup : Time.time; }
    }
    float now;
    // Update is called once per frame
    void Update()
    {
        if (isTimer)
        {
            timeNow = Time_ - offsetTime;
            now = timeNow - timeStart;
            if (updateEvent != null)
                updateEvent(Mathf.Clamp01(now / timeTarget));
            if (now > timeTarget)
            {
                if (onCompleted != null)
                    onCompleted();
                if (!isRepeate)
                    destory();
                else
                    reStartTimer();
            }
        }
    }
    public float GetLeftTime()
    {
        return Mathf.Clamp(timeTarget - now, 0, timeTarget);
    }
    void OnApplicationPause(bool isPause_)
    {
        if (isPause_)
        {
            pauseTimer();
        }
        else
        {
            connitueTimer();
        }
    }

    /// <summary>
    /// 計時結束
    /// </summary>
    public void destory()
    {
        isTimer = false;
        isEnd = true;
        if (isDestory)
            Destroy(gameObject);
    }
    float _pauseTime;
    /// <summary>
    /// 暫停計時
    /// </summary>
    public void pauseTimer()
    {
        if (isEnd)
        {
            if (isLog) Debug.LogWarning("計時已經結束!");
        }
        else
        {
            if(isTimer)
	   {
            	isTimer = false;
            	_pauseTime= Time_;
	   }	
        }
    }
    /// <summary>
    /// 繼續計時
    /// </summary>
    public void connitueTimer()
    {
        if (isEnd)
        {
            if (isLog) Debug.LogWarning("計時已經結束!請從新計時!");
        }
        else
        {
            if (!isTimer)
            {
                offsetTime += (Time_ - _pauseTime);
                isTimer = true;
            }
        }
    }
    public void reStartTimer()
    {
        timeStart = Time_;
        offsetTime = 0;
    }

    public void changeTargetTime(float time_)
    {
        timeTarget += time_;
    }
    /// <summary>
    /// 開始計時 : 
    /// </summary>
    public void startTiming(float time_, CompleteEvent onCompleted_, UpdateEvent update = null, bool isIgnoreTimeScale_ = true, bool isRepeate_ = false, bool isDestory_ = true)
    {
        timeTarget = time_;
		if (onCompleted_ != null)
            onCompleted = onCompleted_;
		if (update != null)
            updateEvent = update;
        isDestory = isDestory_;
        isIgnoreTimeScale = isIgnoreTimeScale_;
        isRepeate = isRepeate_;

        timeStart = Time_;
        offsetTime = 0;
        isEnd = false;
        isTimer = true;

    }
    /// <summary>
    /// 創建計時器:名字
    /// </summary>
    public static Timer createTimer(string gobjName = "Timer")
    {
        GameObject g = new GameObject(gobjName);
        Timer timer = g.AddComponent<Timer>();
        return timer;
    }

}



以上是計時器功能的實現;怎麼用這個計時器呢?


我們可以在需要計時器的腳本中這樣去創建一個計時器:


實現代碼:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{

	// Use this for initialization
	void Start ()
	{
		// 創建計時器
		Timer timer = Timer.createTimer ("Timer");
		//開始計時
		timer.startTiming (1, OnComplete, OnProcess);
	}
	
	// Update is called once per frame
	void Update ()
	{
	
	}
	// 計時結束的回調
	void OnComplete ()
	{
		Debug.Log ("complete !");
	}
	// 計時器的進程
	void OnProcess (float p)
	{
		Debug.Log ("on process " + p);
	}
}

測試腳本中只寫出瞭如何創建和簡單使用計時器,像一些控制計時器的暫停,繼續,獲取剩餘時間等等一系列的功能可以自己測試一下。


發佈了37 篇原創文章 · 獲贊 16 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章