UGUI—倒计时Text

作者:追风剑情 发布于:2019-10-16 17:49 分类:Unity3d

示例

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Serialization;
using UnityEngine.Events;
using UnityEngine.EventSystems;

/// <summary>
/// 倒计时Text
/// </summary>
public class UICountdownText : MonoBehaviour
{
    [SerializeField]
    private Text m_Text;
    [SerializeField]
    private int m_RemainSecond; //剩余时间(单位:秒)
    private int second;
    private int minute;
    private int hour;
    private float startTime;
    private float endTime;
    private float lastTime;
    private bool m_Play = false;

    [Serializable]
    public class OnFinishedEvent : UnityEvent { }

    // 防止序列化变量重命名后丢失引用
    [FormerlySerializedAs("onFinished")]
    [SerializeField]
    private OnFinishedEvent m_OnFinished = new OnFinishedEvent();

    void Awake()
    {
        if (m_Text == null)
            m_Text = this.GetComponent<Text>();
        SetRemainSecond(m_RemainSecond);
    }

    void Update()
    {
        if (!m_Play)
            return;

        if (Time.time - lastTime < 1)
            return;
        lastTime = Time.time;

        string cd = string.Empty;
        if (hour > 0) {
            cd = string.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
        }else if(minute > 0){
            cd = string.Format("{0:D2}:{1:D2}", minute, second);
        }else{
            cd = string.Format("{0:D2}", second);
        }

        if (m_Text != null)
            m_Text.text = cd;
        
        CalculateTime();

        if (m_RemainSecond < 0)
        {
            m_Play = false;
            m_OnFinished.Invoke();
        }
    }

    public void SetRemainSecond(int value)
    {
        m_RemainSecond = value;
        startTime = Time.time;
        endTime = startTime + m_RemainSecond;
        m_Play = true;
        CalculateTime();
    }

    public void SetColor(Color color)
    {
        if (m_Text != null)
            m_Text.color = color;
    }

    private void CalculateTime()
    {
        m_RemainSecond = (int)(endTime - Time.time);
        second = m_RemainSecond % 60;
        minute = (m_RemainSecond / 60) % 60;
        hour = (m_RemainSecond / 3600);
    }
}


运行测试
22222.gif

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号