簡要分析Unity計時器指令碼Timer的用法(附代碼)

來源:互聯網
上載者:User
計時器:

Timer用法:
第一種:指令碼加到物體上,勾選"自動計時"。
第二種:指令碼加到物體上,調用timer.start()方法啟動。
第三種:代碼中動態添加Timer指令碼。

using UnityEngine;public class TimerTest : MonoBehaviour {    private void Start () {        // 建立一個Timer並開始計時        gameObject.AddComponent<Timer>().start(1.5f, onTimeup);        // 倒計時3秒        gameObject.AddComponent<Timer>().start(1, 3, onCD, onCDEnd);        // 無限計數(repeatCount為<=0時 無限重複)        gameObject.AddComponent<Timer>().start(1, -1, onCount, null);        // Timer API        Timer timer = gameObject.AddComponent<Timer>();        timer.delay = 10;// 延遲10秒開始        timer.start();  // 開始計時        timer.stop();   // 暫停計時        timer.reset();  // 重設已計時的時間和次數        timer.restart();// 重新開始計時 reset() + start()    }    /// <summary> 正常計時 </summary>    private void onTimeup(Timer timer) {        print("計時完成");    }    /// <summary> 倒計時間隔 </summary>    private void onCD(Timer timer) {        print(timer.repeatCount - timer.currentCount); // 3, 2, 1    }    /// <summary> 倒計時結束 </summary>    private void onCDEnd(Timer timer) {        print(timer.repeatCount - timer.currentCount); // 0    }    /// <summary> 無限計數 </summary>    private void onCount(Timer timer) {        print(timer.currentCount); // 1, 2, 3……    }}

Timer API:

// 開始/繼續計時public void start() {}// 暫停計時public void stop() {}// 停止Timer並重設資料public void reset() {}// 重設資料並重新開始計時public void restart() {}// 開始計時 time時間(秒) onComplete(Timer timer)計時完成回調事件public void start(float time, TimerCallback onComplete) {}// 開始計時 interval計時間隔 repeatCount重複次數 onComplete(Timer timer)計時完成回調事件public void start(float interval, int repeatCount, TimerCallback onComplete) {}// 開始計時 interval計時間隔 repeatCount重複次數// onInterval(Timer timer)計時間隔回調事件// onComplete(Timer timer)計時完成回調事件public void start(float interval, int repeatCount, TimerCallback onInterval, TimerCallback onComplete) {}

Timer.cs

using UnityEngine;using UnityEngine.Events;/// <summary>/// 計時器/// <para>ZhangYu 2018-04-08</para>/// </summary>public class Timer : MonoBehaviour {    // 延遲時間(秒)    public float delay = 0;    // 間隔時間(秒)    public float interval = 1;    // 重複次數    public int repeatCount = 1;    // 自動計時    public bool autoStart = false;    // 自動銷毀    public bool autoDestory = true;    // 目前時間    public float currentTime = 0;    // 當前次數    public int currentCount = 0;    // 計時間隔    public UnityEvent onIntervalEvent;    // 計時完成    public UnityEvent onCompleteEvent;    // 回調事件代理    public delegate void TimerCallback(Timer timer);    // 上一次間隔時間    private float lastTime = 0;    // 計時間隔    private TimerCallback onIntervalCall;    // 計時結束    private TimerCallback onCompleteCall;    private void Start () {        enabled = autoStart;    }    private void FixedUpdate () {        if (!enabled) return;        addInterval(Time.deltaTime);    }    /// <summary> 增加間隔時間 </summary>    private void addInterval(float deltaTime) {        currentTime += deltaTime;        if (currentTime < delay) return;        if (currentTime - lastTime >= interval) {            currentCount++;            lastTime = currentTime;            if (repeatCount <= 0) {                // 無限重複                if (currentCount == int.MaxValue) reset();                if (onIntervalCall != null) onIntervalCall(this);                if (onIntervalEvent != null) onIntervalEvent.Invoke();            } else {                if (currentCount < repeatCount) {                    //計時間隔                    if (onIntervalCall != null) onIntervalCall(this);                    if (onIntervalEvent != null) onIntervalEvent.Invoke();                } else {                    //計時結束                    stop();                    if (onCompleteCall != null) onCompleteCall(this);                    if (onCompleteEvent != null) onCompleteEvent.Invoke();                    if (autoDestory && !enabled) Destroy(this);                }            }         }    }    /// <summary> 開始/繼續計時 </summary>    public void start() {        enabled = autoStart = true;    }    /// <summary> 開始計時 </summary>    /// <param name="time">時間(秒)</param>    /// <param name="onComplete(Timer timer)">計時完成回調事件</param>    public void start(float time, TimerCallback onComplete) {        start(time, 1, null, onComplete);    }    /// <summary> 開始計時 </summary>    /// <param name="interval">計時間隔</param>    /// <param name="repeatCount">重複次數</param>    /// <param name="onComplete(Timer timer)">計時完成回調事件</param>    public void start(float interval, int repeatCount, TimerCallback onComplete) {        start(interval, repeatCount, null, onComplete);    }    /// <summary> 開始計時 </summary>    /// <param name="interval">計時間隔</param>    /// <param name="repeatCount">重複次數</param>    /// <param name="onInterval(Timer timer)">計時間隔回調事件</param>    /// <param name="onComplete(Timer timer)">計時完成回調事件</param>    public void start(float interval, int repeatCount, TimerCallback onInterval, TimerCallback onComplete) {        this.interval = interval;        this.repeatCount = repeatCount;        onIntervalCall = onInterval;        onCompleteCall = onComplete;        reset();        enabled = autoStart = true;    }    /// <summary> 暫停計時 </summary>    public void stop() {        enabled = autoStart = false;    }    /// <summary> 停止Timer並重設資料 </summary>    public void reset(){        lastTime = currentTime = currentCount = 0;    }    /// <summary> 重設資料並重新開始計時 </summary>    public void restart() {        reset();        start();    }}

TimerEditor.cs

using UnityEditor;using UnityEngine;/// <summary>/// 計時器 編輯器/// <para>ZhangYu 2018-04-08</para>/// </summary>[CanEditMultipleObjects][CustomEditor(typeof(Timer))]public class TimerEditor : Editor {    public override void OnInspectorGUI() {        Timer script = (Timer)target;        // 重繪GUI        EditorGUI.BeginChangeCheck();        // 公開屬性        drawProperty("delay", "延遲時間(秒)");        drawProperty("interval", "間隔時間(秒)");        drawProperty("repeatCount", "重複次數");        if (script.repeatCount <= 0) EditorGUILayout.LabelField(" ", "<=0 時無限重複", GUILayout.ExpandWidth(true));        EditorGUILayout.BeginHorizontal();        drawProperty("autoStart", "自動計時");        drawProperty("autoDestory", "自動銷毀");        EditorGUILayout.EndHorizontal();        // 唯讀屬性        GUI.enabled = false;        drawProperty("currentTime", "目前時間(秒)");        drawProperty("currentCount", "當前次數");        GUI.enabled = true;        // 回調事件        drawProperty("onIntervalEvent", "計時間隔事件");        drawProperty("onCompleteEvent", "計時完成事件");        if (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties();    }    private void drawProperty(string property, string label) {        EditorGUILayout.PropertyField(serializedObject.FindProperty(property), new GUIContent(label), true);    }}

相關文章:

用PEAR::Benchmarking之Timer實現PHP程式計時

如何使用純PHP實現定時器任務(Timer),定時器timer

相關視頻:

玩轉javascript之有聲計算機執行個體

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.