Unity 倒计时

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using UnityEngine.UI;
using System;
using TMPro;
public class TimeCountdown :MonoBehaviour
{
    public UnityEngine.Events.UnityEvent onTimeCountDown;
    public TextMeshProUGUI text;
    public float TotleTime = 30;

    float startTime;

 

    float EndTime;

    float CurTime;

    bool startT;

    public void SetTotleTime(float totleTime) {
        TotleTime = totleTime;
        text.text = StringFormat(0);
    }

    public void StartCountDown(float totleTime)
    {
        TotleTime = totleTime;
        startTime = Time.time;
        startT = true;
        SetCurTimeZero();
    }

    public float EndCountDown()
    {
        EndTime = CurTime;
 
        startT = false;
        return CurTime;
    }

    public void RefreshTime() {
        text.text = StringFormat(0);
    }

    public void CloseCountDown() {
        startT = false;
        RefreshTime();
    }
    void SetCurTimeZero()
    {
        CurTime = 0;
    }
    public void Update()
    {

        if (!startT) return;

        CurTime = Time.time - startTime;

        if (CurTime >= TotleTime)
        {
            CurTime = TotleTime;
            Debug.Log("时间到");
  
            startT = false;
            if (onTimeCountDown != null)
                onTimeCountDown.Invoke();
        }

        if (text != null)
        {
            if (CurTime<=0) CurTime = 0;
           
            text.text = StringFormat(CurTime);
        }
    }



    private string StringFormat(float time)
    {

        var temp = TotleTime - time;

        var t = TempFormat(temp);

        var m = Temp2Time((temp / 60));

        var s = Temp2Time((temp % 60));

        var str = string.Format("{0}:{1}", m, s);

        return str;

    }

    private string Temp2Time(float time)
    {
        return time > 10 ? TempFormat((time)) : "0" + TempFormat((time));
    }

    private string TempFormat(float f)
    {
        var t = Mathf.FloorToInt(f);
        return t.ToString();
    }

    public float GetCurTime()
    {
        return CurTime;
    }

    public int getLeftTime()
    {
        return (int)(TotleTime - CurTime); 
    }
}

 

StartCountDown  :  开始倒计时,参数为倒计时时间


GetCurTime   : 获取已用时间


getLeftTime  :   返回剩余时间

 



FR:海涛高软(Hunk Xu) 
QQ技术交流群:386476712

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值