计时器(C#)
很多项目要用到计时器,我就自己包装了一个,倒计时还没加,有时间再加上吧。持续更新
using UnityEngine; using UnityEngine.UI; /// <summary> /// 实现一个计时器 /// </summary> public class Timing : MonoBehaviour { /// <summary> /// 单例模式 /// </summary> public static Timing time; private Text timeText; /// <summary> /// 小时,分钟,秒的数值 /// </summary> private float s = 0; private int h = 0; private int m = 0; //控制是否需要计时 public bool isTiming = false ; void Awake() { time = this; } // Use this for initialization void Start() { } // Update is called once per frame void Update() { if (isTiming) { TimingUpdate(); } } public void TimingUpdate() { s = s + Time.deltaTime; if (s >= 60) { s -= 60; m = m + 1; if (m == 60) { m -= 60; h += 1; } } textFunc(); } /// <summary> /// 更新时间并更新显示 /// </summary> public void textFunc() { if(timeText != null) timeText.text = ToString(h, true) + ToString(m, true) + ToString((int)s, false); } public string ToString(int i,bool isNeed) { string x = ""; if (i < 10) { x = "0" + i; } else { x = i.ToString(); } if (isNeed) x += ":"; return x; } /// <summary> /// 暂停计时,调用continueTimingFunc会接着上一次继续计时 /// </summary> public void pauseTimingFunc() { isTiming = false; } /// <summary> /// 继续计时 /// </summary> public void continueTimingFunc() { isTiming = true; } /// <summary> /// 开始计时 /// </summary> /// <param name="t">要改变的TEXT组件</param> public void startTimingFunc(Text t) { isTiming = true; timeText = t; } /// <summary> /// 结束计时,会清空当前计时时间 /// </summary> public void stopTimingFunc() { isTiming = false; s = 0; m = 0; h = 0; } }