c# 在Unity 总实现简单的倒计时,正计时功能

51 篇文章 1 订阅

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;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值