Brief analysis of the use of the Unity Timer script timer (with code)

Source: Internet
Author: User
Tags repetition
Timer:





Timer usage:
The first type: The script is added to the object, tick "auto-timer".
The second type: The script is added to the object and the Timer.start () method is called to start.
The third type: Add the timer script dynamically in the code.


Using UnityEngine;

 

Public class TimerTest : MonoBehaviour {

 

    Private void Start () {

        // Create a Timer and start timing

        gameObject.AddComponent<Timer>().start(1.5f, onTimeup);

 

        // Countdown 3 seconds

        gameObject.AddComponent<Timer>().start(1, 3, onCD, onCDEnd);

 

        // Unlimited count (repeated count is <=0, unlimited repeat)

        gameObject.AddComponent<Timer>().start(1, -1, onCount, null);

 

        // Timer API

        Timer timer = gameObject.AddComponent<Timer>();

        Timer.delay = 10;// delay 10 seconds to start

        Timer.start(); // start timing

        Timer.stop(); // Pause timing

        Timer.reset(); // Reset the time and number of times that have been counted

        Timer.restart();// Restart timing reset() + start()

    }

 

    /// <summary> normal timing </summary>

    Private void onTimeup(Timer timer) {

        Print("Time Completion");

    }

 

    /// <summary> countdown interval </summary>

    Private void onCD(Timer timer) {

        Print(timer.repeatCount - timer.currentCount); // 3, 2, 1

    }

 

    /// <summary> Countdown ends </summary>

    Private void onCDEnd(Timer timer) {

        Print(timer.repeatCount - timer.currentCount); // 0

    }

 

    /// <summary> infinite count </summary>

    Private void onCount(Timer timer) {

        Print(timer.currentCount); // 1, 2, 3...

    }

 

}


Timer API:


// start/continue timing

Public void start() {}

 

// pause timing

Public void stop() {}

 

// stop the Timer and reset the data

Public void reset() {}

 

// reset the data and start timing again

Public void restart() {}

 

// Start timing time (seconds) onComplete (Timer timer) timing completion callback event

Public void start(float time, TimerCallback onComplete) {}

 

// Start timing interval timing interval repeatCount repetition number onComplete(Timer timer) timing completion callback event

Public void start(float interval, int repeatCount, TimerCallback onComplete) {}

 

// start timing interval timing interval repeatCount repetitions

// onInterval(Timer timer) timing interval callback event

// onComplete(Timer timer) timed completion callback event

Public void start(float interval, int repeatCount, TimerCallback onInterval, TimerCallback onComplete) {}


Timer.cs


Using UnityEngine;

Using UnityEngine.Events;

 

/// <summary>

/// timer

/// <para>ZhangYu 2018-04-08</para>

/// </summary>

Public class Timer : MonoBehaviour {

 

    // delay time (seconds)

    Public float delay = 0;

    // interval time (seconds)

    Public float interval = 1;

    // repeat times

    Public int repeatCount = 1;

    // automatic timing

    Public bool autoStart = false;

    // automatic destruction

    Public bool autoDestory = true;

    // current time

    Public float currentTime = 0;

    // current number of times

    Public int currentCount = 0;

    // timing interval

    Public UnityEvent onIntervalEvent;

    // timing is complete

    Public UnityEvent onCompleteEvent;

    // callback event proxy

    Public delegate void TimerCallback(Timer timer);

    // last interval

    Private float lastTime = 0;

    // timing interval

    Private TimerCallback onIntervalCall;

    // end of time

    Private TimerCallback onCompleteCall;

 

    Private void Start () {

        Enabled = autoStart;

    }

 

    Private void FixedUpdate () {

        If (!enabled) return;

        addInterval(Time.deltaTime);

    }

 

    /// <summary> increase interval </summary>

    Private void addInterval(float deltaTime) {

        currentTime += deltaTime;

        If (currentTime < delay) return;

        If (currentTime - lastTime >= interval) {

            currentCount++;

            lastTime = currentTime;

            If (repeatCount <= 0) {

                // Unlimited repetition

                If (currentCount == int.MaxValue) reset();

                If (onIntervalCall != null) onIntervalCall(this);

                If (onIntervalEvent != null) onIntervalEvent.Invoke();

            } else {

                If (currentCount < repeatCount) {

                    //Time interval

                    If (onIntervalCall != null) onIntervalCall(this);

                    If (onIntervalEvent != null) onIntervalEvent.Invoke();

                } else {

                    //Time is over

                    Stop();

                    If (onCompleteCall != null) onCompleteCall(this);

                    If (onCompleteEvent != null) onCompleteEvent.Invoke();

                    If (autoDestory && !enabled) Destroy(this);

                }

            }

        }

    }

 

    /// <summary> start/continue timing </summary>

    Public void start() {

        Enabled = autoStart = true;

    }

 

    /// <summary> start timing </summary>

    /// <param name="time">time (seconds)</param>

    /// <param name="onComplete(Timer timer)">Timed completion callback event</param>

    Public void start(float time, TimerCallback onComplete) {

        Start(time, 1, null, onComplete);

    }

 

    /// <summary> start timing </summary>

    /// <param name="interval">time interval</param>

    /// <param name="repeatCount">Number of repetitions</param>

    /// <param name="onComplete(Timer timer)">Timed completion callback event</param>

    Public void start(float interval, int repeatCount, TimerCallback onComplete) {

        Start(interval, repeatCount, null, onComplete);

    }

 

    /// <summary> start timing </summary>

    /// <param name="interval">time interval</param>

    /// <param name="repeatCount">Number of repetitions</param>

    /// <param name="onInterval(Timer timer)">Timed Interval Callback Event</param>

    /// <param name="onComplete(Timer timer)">Timed completion callback event</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> pause timing </summary>

    Public void stop() {

        Enabled = autoStart = false;

    }

 

    /// <summary> Stop Timer and reset data </summary>

    Public void reset(){

        lastTime = currentTime = currentCount = 0;

    }

 

    /// <summary> Reset data and start timing again </summary>

    Public void restart() {

        Reset();

        Start();

    }

 

}


TimerEditor.cs


Using UnityEditor;

Using UnityEngine;

 

/// <summary>

/// Timer Editor

/// <para>ZhangYu 2018-04-08</para>

/// </summary>

[CanEditMultipleObjects]

[CustomEditor(typeof(Timer))]

Public class TimerEditor : Editor {

 

    Public override void OnInspectorGUI() {

        Timer script = (Timer)target;

 

        // redraw the GUI

        EditorGUI.BeginChangeCheck();

 

        // public property

        drawProperty("delay", "delay time (seconds)");

        drawProperty("interval", "interval (seconds)");

        drawProperty("repeatCount", "number of repetitions");

        If (script.repeatCount <= 0) EditorGUILayout.LabelField(" ", "Infinitely repeats when <=0", GUILayout.ExpandWidth(true));

        EditorGUILayout.BeginHorizontal();

        drawProperty("autoStart", "automatic timing");

        drawProperty("autoDestory", "automatic destruction");

        EditorGUILayout.EndHorizontal();

 

        // read-only property

        GUI.enabled = false;

        drawProperty("currentTime", "current time (seconds)");

        drawProperty("currentCount", "current number");

        GUI.enabled = true;

 

        // callback event

        drawProperty("onIntervalEvent", "Time Interval Event");

        drawProperty("onCompleteEvent", "Time Completion Event");

        If (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties();

    }

 

    Private void drawProperty(string property, string label) {

        EditorGUILayout.PropertyField(serializedObject.FindProperty(property), new GUIContent(label), true);

    }

 

} 


Related articles:



Using the pear::benchmarking timer to implement the PHP program timing



How to use pure PHP to implement timer task (timer), timers timer



Related videos:



Examples of audio calculators for playing with JavaScript


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.