c# 在Unity 总实现简单的倒计时,正计时功能
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour {
public bool startCount = false;
public static Timer Instance;
// Use this for initialization
void Awake()
{
Instance = this;
//UI_InitSelectCreat.Instance.InitCompleteAction += StartCount; // 初始化完成开始计时
}
void Start() {
}
// Update is called once per frame
void Update() {
if (startCount) {
Timer1(); //倒计时
Timer2();//正计时
}
}//10:00
string s;
string m;
private float totalTime = 0;
public float second = 0;
public float min = 10;
public Text txtTimer;
private void Timer1()
{
//累加每帧消耗时间
totalTime += Time.deltaTime;
if (totalTime >= 1)//每过1秒执行一次
{
second--;
if (second < 0)
{
second = 59;
min--;
}
totalTime = 0;
}
s = second.ToString();
m = min.ToString();
if (second < 10) {
s = string.Format("0{0}", second);
}
if (min < 10) {
m = string.Format("0{0}", min);
}
txtTimer.text = string.Format("{0}:{1}", m, s);
if (min < 0) {
Debug.Log("时间结束了0-0");
}
}
private float totalTime2 = 0;
public float second2 = 0;
public float min2 = 0;
string s2;
string m2;
public string timeAllstr2;
private void Timer2()
{
//累加每帧消耗时间
totalTime2 += Time.deltaTime;
if (totalTime2 >= 1)//每过1秒执行一次
{
second2++;
if (second2 > 59)
{
second2 = 0;
min2++;
Debug.Log("x过来一秒xx");
}
totalTime2 = 0;
}
s2 = second2.ToString();
m2 = min2.ToString();
if (min2 > 59) {
min2 = 0;
second2 = 0;
}
if (second2 < 10)
{
s2 = string.Format("0{0}", second2);
}
if (min2 < 10)
{
m2 = string.Format("0{0}", min2);
}
timeAllstr2 = string.Format("{0}分{1}秒", m2, s2);
}
public void StartCount()
{
startCount = true;
}
public void StopCount()
{
startCount = false;
}
}