Cuenta regresiva de compilación de Unity

Efecto: (cuenta regresiva cada segundo según el formato especificado, y la cuenta regresiva de los últimos 3 segundos se volverá roja)

paso:

1. Haga clic con el botón derecho del mouse en el panel Jerarquía de Unity -> IU -> Texto, de la siguiente manera:

2. Cree un nuevo script de C# y vincúlelo al TextTimer de la imagen de arriba. El código de C# es el siguiente:

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

o: (recomendado)

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. Simplemente ejecútelo en Unity

Supongo que te gusta

Origin blog.csdn.net/ChaoChao66666/article/details/123423560
Recomendado
Clasificación