倒计时更新组件 每秒更新一次时间文字

来源:互联网 发布:最短距离算法 编辑:程序博客网 时间:2024/05/10 14:43
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
/// <summary>
/// Time text update倒计时更新组件 每秒更新一次时间文字
/// </summary>
public class TimeTextUpdate : MonoBehaviour {

    Text text;
    long time;
    long increment = -1;
    /// <summary>
    /// Add the specified gotime and s.
    /// </summary>
    /// <param name="go">Go.</param>
    /// <param name="time">Time</param>
    public static void Add(GameObject go,long time,long increment= -1){
        //毫秒 <==  * 1000;
        TimeTextUpdate timeTextUpdate = go.GetComponent<TimeTextUpdate>() ;
        if(timeTextUpdate == null){
            timeTextUpdate = go.AddComponent<TimeTextUpdate>() ;
        }
        timeTextUpdate.time = time;
        timeTextUpdate.increment = increment;
        timeTextUpdate.StartUpdate();
    }

    // Use this for initialization
    void Start () {

    }

    void _setInterval(){
        text.text = _getTimeStr(time);
        time += increment;
    }
    /// <summary>
    /// _gets the time string.
    /// </summary>
    /// <returns>The time string.</returns>
    /// <param name="timeLong">Time long.毫秒</param>
    string _getTimeStr(long timeLong){
        if(timeLong <= 0){ 
            StopUpdate();
            if(text != null){
                Hashtable data = new Hashtable();
                data.Add("go",text.gameObject);
                EventManager.I.send("OnTimeTextUpdateCmp",data);
            }
            return "";
        }
        long h = timeLong/3600;
        long m = (timeLong%3600)/60;
        long s = (timeLong%3600)%60;
        string str = (h > 0 ? (h +"小时") :"" ) + (m > 0 ? (m +"") :"" ) + (s > 0 ? (s +"") :"" );
        return str;
    }

    public void StartUpdate () {
        StopUpdate();
        text = gameObject.GetComponent<Text>();
        if(text != null && time > 0)
            this.InvokeRepeating("_setInterval"1.0f1.0f);
    }

    public void StopUpdate () {
        this.CancelInvoke();
    }

    void OnDestroy() {
        StopUpdate ();
    }
}
0 0
原创粉丝点击