unity3d---倒计时代码

unity3d---倒计时代码

设计实现:

1.在场景属性中设置倒计时的时间

2.倒计时完毕,执行操作(在这里是跳转场景)

界面设计:

脚本代码:

 1 using UnityEngine;
 2 
 3 using System.Collections;
 4 
 5 using UnityEngine;
 6 
 7 using System.Collections;
 8 
 9 using UnityEngine.UI;
10 
11 public class timer : MonoBehaviour {
12 
13     public int TotalTime=90;//总时间
14 
15     public Text TimeText;//在UI里显示时间
16     public string LoadsceneName;
17 
18     private int mumite;//
19 
20     private int second;//
21 
22     void Start(){
23 
24         StartCoroutine(startTime());   //运行一开始就进行协程
25 
26     }
27 
28     public IEnumerator  startTime() {
29 
30         while (TotalTime >= 0) {
31 
32             //Debug.Log(TotalTime);//打印出每一秒剩余的时间
33 
34             yield return new WaitForSeconds(1);//由于开始倒计时,需要经过一秒才开始减去1秒,
35                                                //所以要先用yield return new WaitForSeconds(1);然后再进行TotalTime--;运算
36 
37             TotalTime--;
38 
39             TimeText.text="Time:"+TotalTime;
40 
41             if (TotalTime<= 0){                //如果倒计时剩余总时间为0时,就跳转场景
42 
43                 LoadScene();
44 
45             }
46 
47             mumite=TotalTime/60; //输出显示分
48 
49             second=TotalTime%60; //输出显示秒
50 
51             string length = mumite.ToString ();
52                 if (second >= 10) {
53 
54                     TimeText.text = "0" + mumite + ":" + second;
55                 }     //如果秒大于10的时候,就输出格式为 00:00
56 
57                 else
58                     TimeText.text = "0" + mumite + ":0" + second;      //如果秒小于10的时候,就输出格式为 00:00
59 
60             } 
61 
62 
63     }
64 
65     void LoadScene() {
66 
67         Application.LoadLevel(LoadsceneName);//倒计时结束跳转到场景,LoadsceneName可以在外部修改
68 
69     }
70 
71 }
View Code
原文地址:https://www.cnblogs.com/jiangyuzhen/p/6518725.html