search
HomeBackend DevelopmentC#.Net TutorialBrief analysis of the usage of Unity timer script Timer (with code)

Timer rendering:
Brief analysis of the usage of Unity timer script Timer (with code)

Timer usage:
First type: Add the script to the object and check "Automatic timing".
Second type: Add the script to the object and call the timer.start() method to start.
Third method: Dynamically add the Timer script in the code.

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);
    }

}

Related articles:

Use PEAR::Benchmarking’s Timer to implement PHP program timing

How to use pure PHP to implement timer tasks (Timer ), timer timer

Related videos:

Play with javascript audio calculator example

The above is the detailed content of Brief analysis of the usage of Unity timer script Timer (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software