03、三种简单的计时器

1、计时器在游戏中的使用次数很多,以下是三种简单的计时器写法

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.UI;
 5 
 6 public class Timer : MonoBehaviour
 7 {
 8     private Text textTime;
 9     private int second = 20;
10 
11     private void Awake()
12     {
13         textTime = this.GetComponent<Text>();
14     }
15     private void Update()
16     {
17         //Timer_01();
18        // Timer_02();
19     }
20 
21     //第一种方式的计时器
22     private float nextTimer_1 = 1;   //下次修改时间
23     private float nextTime_1 = 1;    //一次间隔是多少
24     private void Timer_01()
25     {
26         if (nextTimer_1 <= Time.time)
27         {
28             //到了1秒
29             second--;
30             if (second >= 0)
31             {
32                 textTime.text = string.Format("{0:d2}:{1:d2}", (int)second / 60, (int)second % 60);
33                 nextTimer_1 += nextTime_1;  //将计时器当前的存储加上程序运行的时间
34             }
35         }
36     }
37 
38     //第二种方式的计时器
39     private float nextTime_2_1 = 0;
40     private float nextTime_2_2 = 1;  //时间间隔
41     private void Timer_02()
42     {
43         nextTime_2_1 += Time.deltaTime;
44         if (nextTime_2_1 >= nextTime_2_2)
45         {
46             //到了1秒了
47             second--;
48             if (second >= 0)
49             {
50                 textTime.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
51                 nextTime_2_1 = 0;
52             }
53         }
54     }
55 
56     //第三种是使用InvokeRepeating,来指定起始时间,重复调用方法的间隔
57     private void Start()
58     {
59         InvokeRepeating("Timer_03", 0, 1);
60     }
61     private void Timer_03()
62     {
63         second--;
64         if(second<=0)
65         {
66             CancelInvoke("Timer_03");   //如果时间为0了,则就要终止循环调用了
67         }
68         textTime.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
69     }
70 }
原文地址:https://www.cnblogs.com/zhh19981104/p/9574381.html