zoukankan      html  css  js  c++  java
  • 关于Unity中定时器的简易使用

     定时器

    一段指定的时间后执行某个函数或者某个语句

    用法

    //定时器写法1

    flaot total_time;
    void Update(){
      this.total_time += (Time.deltaTime);
      if(total_time > = 5)//5秒后停止
      {
        return;
      }
    }

    //定时器写法2

    void Hello(){
    
    }
    this.Invoke("Hello",5.0f);//5秒后执行Hello函数

    void Hello(){
    
    }
    this.InvokeReapting("Hello",3,3);//每隔3秒调用一次Hello函数
    this.CancelInvoke("Hello");//取消重复定时器

    //定时器写法3

    协程的定时中断

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class game : MonoBehaviour
    {
        private int level = 3;
        // Use this for initialization
        void Start()
        {
            //启动一个协程,必须是继承自MonoBehaviour才能使用
            this.StartCoroutine(this.con_entry());
    
            //主线程依然在执行
            //...
        }
    
        //协程和主线程是在同一个线程里面的,不会有什么线程切换
        //协程的入口函数
        IEnumerator con_entry()
        {
            //协程的代码
            Debug.Log("con_entry run!!");
            Debug.Log("level:" + this.level);//也能够拿到this的变量
            //end
    
            yield return new WaitForSeconds(3);//定时,使用yield中断协程程序,设置3秒中之后才中断协程
    
            //协程结束以后的代码,比如去网上捞一个什么东西,下载图片之类的,捞完之后的操作
            //end
        }
    
        // Update is called once per frame
        void Update()
        {
    
        }
    }

    //定时器写法4

    多线程里面的线程休眠方法

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using System.Threading;//多线程要用到的库,多线程对象所在的名字空间
    
    public class game : MonoBehaviour
    {
        // Use this for initialization
        void Start()
        {
    
            //创建一个线程t1,关联入口函数
            Thread t1 = new Thread(this.thread_run);//不是像协程那样直接运行
            t1.Start();//这里才开始执行,开启线程
    
        }
    
        //线程t1的入口函数
        void thread_run()
        {
            int i = 0;
            while (i < 10)
            {//打印10次,每次直接间隔3秒
                Debug.Log("thread_run");
                i++;
                Thread.Sleep(3000);//让线程休息3秒钟,有点像定时器,里面参数是毫秒为单位的
            }
        }
    
        // Update is called once per frame
        void Update()
        {
    
        }
    }
  • 相关阅读:
    python爬虫练习5——新闻联播
    python爬虫练习4——腾讯视频评论提取
    python爬虫练习3——豆瓣电影
    python爬虫练习2——豆瓣读书
    python爬虫练习1——百度阅读榜
    微信小程序音频视频下载(fiddler抓包)
    4. Median of Two Sorted Arrays
    42.trapping-rain-water
    3.lengthOfLongestSubstring
    1.two sum
  • 原文地址:https://www.cnblogs.com/HangZhe/p/7267859.html
Copyright © 2011-2022 走看看