zoukankan      html  css  js  c++  java
  • 【Unity】制作简易定时器(Timer)

    最近开始学习Unity,也想开始学习写一些简单的博客。
    在网上学习了一些关于定时器的写法,在此简单总结一下,方便自己以后用到时查阅。

    需求:制作定时器,运行3秒后执行第一次,之后每隔3秒执行一次操作。

    方法①:使用变量在Update中计时,也是各种书中最常见的方法。

    public class TestTimer : MonoBehaviour {
    
        private float lastTime;
        private float curTime;
    
        void Start () {
            lastTime = Time.time;
        }
    
        void Update () {
            curTime = Time.time;
            if (curTime - lastTime >= 3)
            {
                Debug.Log("work");
                lastTime = curTime;
               }
        }
    }

    方法②:使用协程Coroutine

    public class TestTimer : MonoBehaviour {
    
        void Start () {
            StartCoroutine(Do()); // 开启协程
        }
    
        IEnumerator Do()
        {
            while (true) // 还需另外设置跳出循环的条件
            {
                yield return new WaitForSeconds(3.0f);
                Debug.Log("work");
            }
        }
    }

    方法③:使用InvokeRepeating

    public class TestTimer : MonoBehaviour {
    
        void Start () {
            InvokeRepeating("Do", 3.0f, 3.0f);
        }
    
        void Do()
        {
            Debug.Log("work");
        }
    }

    个人认为,使用InvokeRepeating调用写法最简洁。

  • 相关阅读:
    linux sed命令详解
    SQL注入基础知识
    DC-7
    DC-6
    DC-5
    DC-4
    DC-3
    DC-2
    pentestlabs
    任意文件读取和下载
  • 原文地址:https://www.cnblogs.com/guxin/p/7129033.html
Copyright © 2011-2022 走看看