Unity 制作倒计时

效果:(按指定格式每秒倒计时,最后3秒倒计时变红)

步骤:

1.在Unity的Hierarchy面板点击鼠标右键->UI->Text,如下:

2.新建一个C#脚本,与上图中的TextTimer绑定,C#代码如下:

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


{
    private Text txtTimer;
    public float second;

    private void Start()
    {
        txtTimer = this.GetComponent<Text>();
    }

    private void Update()
    {

        if (second > 0)
        {
            second = second - Time.deltaTime;
            if (second / 60 < 1)
            {
                if (second < 4)
                {
                    txtTimer.color = Color.red;
                }
                txtTimer.text = string.Format("00:{0:d2}", (int)second % 60);
            }
            else
            {
                txtTimer.text = string.Format("{0:d2}:{1:d2}", (int)second / 60, (int)second % 60);
            }
        }
        else
        {
            txtTimer.text = "00:00";
            txtTimer.color = Color.red;
        }
        
    }
}

或:(推荐)

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


public class CountdownTimer : MonoBehaviour
{
    private Text txtTimer;
    public float second;

    private void Start()
    {
        // 1.查找组件引用
        txtTimer = this.GetComponent<Text>();
        // 重复调用(被执行的方法名称,第一次执行时间,每次执行间隔时间)
        InvokeRepeating("Timer", 1, 1);
    }

    private void Timer()
    {
        second = second - 1;
        txtTimer.text = string.Format("{0:d2}:{1:d2}", (int)second / 60, (int)second % 60);

        if (second <= 3) 
        {
            txtTimer.color = Color.red;
            if (second <= 0)
            {
                // 取消调用
                CancelInvoke("Timer");
            }
        }
    }
}

3.在Unity中运行即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhichao_97

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值