效果:(按指定格式每秒倒计时,最后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中运行即可

Logo

苏州本地的技术开发者社区,在这里可以交流本地的好吃好玩的,可以交流技术,可以交流招聘等等,没啥限制。

更多推荐