text倒计时

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timert : MonoBehaviour
{
    public int second = 120;

    private Text txtTimer;
    private float nextTime = 1;//下一次改变时间
    // Start is called before the first frame update
    void Start()
    {
        txtTimer = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        Timer1();

    }
    private void Timer1()
    {
        //如果时间到了 
        if (nextTime <= Time.time)
        {
            second--;//119       1:59 
            txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
            nextTime = Time.time + 1;//在当前时间上增加1s

            if (second <= 10) txtTimer.color = Color.red;
            if (second <= 0) enabled = false;
        }
    }

}
using UnityEngine;
using UnityEngine.UI;

public class Timert : MonoBehaviour
{
    public int second = 120;

    private Text txtTimer;
    private float totalTime=0;//下一次改变时间
    // Start is called before the first frame update
    void Start()
    {
        txtTimer = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        Timer2();

    }
    
    private void Timer2()
    {
        //累加每帧消耗时间
        totalTime += Time.deltaTime;

        //如果1s
        if (totalTime >= 1)
        {
            second--;//119       1:59 
            txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
            totalTime = 0;//清空累加的时间
            if (second <= 10) txtTimer.color = Color.red;
            if (second <= 0) enabled = false;
        }
    }


}
using UnityEngine;
using UnityEngine.UI;

public class Timert : MonoBehaviour
{
    public int second = 120;

    private Text txtTimer;
    
    // Start is called before the first frame update
    void Start()
    {
        txtTimer = GetComponent<Text>();
        //重复调用(要执行的方法名称,开始调用时间,调用间隔)
        InvokeRepeating("Timer", 0, 1);
       //延迟调用
        //Invoke("需要调用的方法名称", 调用时间);
    }

  
    private void Timer()
    {
             second--;//119       1:59 
            txtTimer.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
           
            if (second <= 10) txtTimer.color = Color.red;
            // 取消调用
            if (second <= 0) {CancelInvoke("Timer");}
       
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值