溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Unity計(jì)時(shí)器腳本Timer的用法案例

發(fā)布時(shí)間:2020-10-12 17:35:39 來(lái)源:億速云 閱讀:292 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下Unity計(jì)時(shí)器腳本Timer的用法案例,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

計(jì)時(shí)器效果圖:
Unity計(jì)時(shí)器腳本Timer的用法案例

Timer用法:
第一種:腳本加到物體上,勾選"自動(dòng)計(jì)時(shí)"。
第二種:腳本加到物體上,調(diào)用timer.start()方法啟動(dòng)。
第三種:代碼中動(dòng)態(tài)添加Timer腳本。

using UnityEngine;

public class TimerTest : MonoBehaviour {

    private void Start () {
        // 創(chuàng)建一個(gè)Timer并開(kāi)始計(jì)時(shí)
        gameObject.AddComponent<Timer>().start(1.5f, onTimeup);

        // 倒計(jì)時(shí)3秒
        gameObject.AddComponent<Timer>().start(1, 3, onCD, onCDEnd);

        // 無(wú)限計(jì)數(shù)(repeatCount為<=0時(shí) 無(wú)限重復(fù))
        gameObject.AddComponent<Timer>().start(1, -1, onCount, null);

        // Timer API
        Timer timer = gameObject.AddComponent<Timer>();
        timer.delay = 10;// 延遲10秒開(kāi)始
        timer.start();  // 開(kāi)始計(jì)時(shí)
        timer.stop();   // 暫停計(jì)時(shí)
        timer.reset();  // 重置已計(jì)時(shí)的時(shí)間和次數(shù)
        timer.restart();// 重新開(kāi)始計(jì)時(shí) reset() + start()
    }

    /// <summary> 正常計(jì)時(shí) </summary>
    private void onTimeup(Timer timer) {
        print("計(jì)時(shí)完成");
    }

    /// <summary> 倒計(jì)時(shí)間隔 </summary>
    private void onCD(Timer timer) {
        print(timer.repeatCount - timer.currentCount); // 3, 2, 1
    }

    /// <summary> 倒計(jì)時(shí)結(jié)束 </summary>
    private void onCDEnd(Timer timer) {
        print(timer.repeatCount - timer.currentCount); // 0
    }

    /// <summary> 無(wú)限計(jì)數(shù) </summary>
    private void onCount(Timer timer) {
        print(timer.currentCount); // 1, 2, 3……
    }

}

Timer API:

// 開(kāi)始/繼續(xù)計(jì)時(shí)
public void start() {}

// 暫停計(jì)時(shí)
public void stop() {}

// 停止Timer并重置數(shù)據(jù)
public void reset() {}

// 重置數(shù)據(jù)并重新開(kāi)始計(jì)時(shí)
public void restart() {}

// 開(kāi)始計(jì)時(shí) time時(shí)間(秒) onComplete(Timer timer)計(jì)時(shí)完成回調(diào)事件
public void start(float time, TimerCallback onComplete) {}

// 開(kāi)始計(jì)時(shí) interval計(jì)時(shí)間隔 repeatCount重復(fù)次數(shù) onComplete(Timer timer)計(jì)時(shí)完成回調(diào)事件
public void start(float interval, int repeatCount, TimerCallback onComplete) {}

// 開(kāi)始計(jì)時(shí) interval計(jì)時(shí)間隔 repeatCount重復(fù)次數(shù)
// onInterval(Timer timer)計(jì)時(shí)間隔回調(diào)事件
// onComplete(Timer timer)計(jì)時(shí)完成回調(diào)事件
public void start(float interval, int repeatCount, TimerCallback onInterval, TimerCallback onComplete) {}

Timer.cs

using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// 計(jì)時(shí)器
/// <para>ZhangYu 2018-04-08</para>
/// </summary>
public class Timer : MonoBehaviour {

    // 延遲時(shí)間(秒)
    public float delay = 0;
    // 間隔時(shí)間(秒)
    public float interval = 1;
    // 重復(fù)次數(shù)
    public int repeatCount = 1;
    // 自動(dòng)計(jì)時(shí)
    public bool autoStart = false;
    // 自動(dòng)銷毀
    public bool autoDestory = true;
    // 當(dāng)前時(shí)間
    public float currentTime = 0;
    // 當(dāng)前次數(shù)
    public int currentCount = 0;
    // 計(jì)時(shí)間隔
    public UnityEvent onIntervalEvent;
    // 計(jì)時(shí)完成
    public UnityEvent onCompleteEvent;
    // 回調(diào)事件代理
    public delegate void TimerCallback(Timer timer);
    // 上一次間隔時(shí)間
    private float lastTime = 0;
    // 計(jì)時(shí)間隔
    private TimerCallback onIntervalCall;
    // 計(jì)時(shí)結(jié)束
    private TimerCallback onCompleteCall;

    private void Start () {
        enabled = autoStart;
    }

    private void FixedUpdate () {
        if (!enabled) return;
        addInterval(Time.deltaTime);
    }

    /// <summary> 增加間隔時(shí)間 </summary>
    private void addInterval(float deltaTime) {
        currentTime += deltaTime;
        if (currentTime < delay) return;
        if (currentTime - lastTime >= interval) {
            currentCount++;
            lastTime = currentTime;
            if (repeatCount <= 0) {
                // 無(wú)限重復(fù)
                if (currentCount == int.MaxValue) reset();
                if (onIntervalCall != null) onIntervalCall(this);
                if (onIntervalEvent != null) onIntervalEvent.Invoke();
            } else {
                if (currentCount < repeatCount) {
                    //計(jì)時(shí)間隔
                    if (onIntervalCall != null) onIntervalCall(this);
                    if (onIntervalEvent != null) onIntervalEvent.Invoke();
                } else {
                    //計(jì)時(shí)結(jié)束
                    stop();
                    if (onCompleteCall != null) onCompleteCall(this);
                    if (onCompleteEvent != null) onCompleteEvent.Invoke();
                    if (autoDestory && !enabled) Destroy(this);
                }
            } 
        }
    }

    /// <summary> 開(kāi)始/繼續(xù)計(jì)時(shí) </summary>
    public void start() {
        enabled = autoStart = true;
    }

    /// <summary> 開(kāi)始計(jì)時(shí) </summary>
    /// <param name="time">時(shí)間(秒)</param>
    /// <param name="onComplete(Timer timer)">計(jì)時(shí)完成回調(diào)事件</param>
    public void start(float time, TimerCallback onComplete) {
        start(time, 1, null, onComplete);
    }

    /// <summary> 開(kāi)始計(jì)時(shí) </summary>
    /// <param name="interval">計(jì)時(shí)間隔</param>
    /// <param name="repeatCount">重復(fù)次數(shù)</param>
    /// <param name="onComplete(Timer timer)">計(jì)時(shí)完成回調(diào)事件</param>
    public void start(float interval, int repeatCount, TimerCallback onComplete) {
        start(interval, repeatCount, null, onComplete);
    }

    /// <summary> 開(kāi)始計(jì)時(shí) </summary>
    /// <param name="interval">計(jì)時(shí)間隔</param>
    /// <param name="repeatCount">重復(fù)次數(shù)</param>
    /// <param name="onInterval(Timer timer)">計(jì)時(shí)間隔回調(diào)事件</param>
    /// <param name="onComplete(Timer timer)">計(jì)時(shí)完成回調(diào)事件</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> 暫停計(jì)時(shí) </summary>
    public void stop() {
        enabled = autoStart = false;
    }

    /// <summary> 停止Timer并重置數(shù)據(jù) </summary>
    public void reset(){
        lastTime = currentTime = currentCount = 0;
    }

    /// <summary> 重置數(shù)據(jù)并重新開(kāi)始計(jì)時(shí) </summary>
    public void restart() {
        reset();
        start();
    }

}

TimerEditor.cs

using UnityEditor;
using UnityEngine;

/// <summary>
/// 計(jì)時(shí)器 編輯器
/// <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();

        // 公開(kāi)屬性
        drawProperty("delay", "延遲時(shí)間(秒)");
        drawProperty("interval", "間隔時(shí)間(秒)");
        drawProperty("repeatCount", "重復(fù)次數(shù)");
        if (script.repeatCount <= 0) EditorGUILayout.LabelField(" ", "<=0 時(shí)無(wú)限重復(fù)", GUILayout.ExpandWidth(true));
        EditorGUILayout.BeginHorizontal();
        drawProperty("autoStart", "自動(dòng)計(jì)時(shí)");
        drawProperty("autoDestory", "自動(dòng)銷毀");
        EditorGUILayout.EndHorizontal();

        // 只讀屬性
        GUI.enabled = false;
        drawProperty("currentTime", "當(dāng)前時(shí)間(秒)");
        drawProperty("currentCount", "當(dāng)前次數(shù)");
        GUI.enabled = true;

        // 回調(diào)事件
        drawProperty("onIntervalEvent", "計(jì)時(shí)間隔事件");
        drawProperty("onCompleteEvent", "計(jì)時(shí)完成事件");
        if (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties();
    }

    private void drawProperty(string property, string label) {
        EditorGUILayout.PropertyField(serializedObject.FindProperty(property), new GUIContent(label), true);
    }

}

看完了這篇文章,相信你對(duì)Unity計(jì)時(shí)器腳本Timer的用法案例有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI