03三种简单的计时器
Posted zhh19981104
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了03三种简单的计时器相关的知识,希望对你有一定的参考价值。
1、计时器在游戏中的使用次数很多,以下是三种简单的计时器写法
2、代码:
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 }
以上是关于03三种简单的计时器的主要内容,如果未能解决你的问题,请参考以下文章
JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段