1、每帧检查

定义一个时间变量 timer,每帧将此时间减去帧间隔时间 Time.deltaTime,如果小于或者等于零,说明定时器到了,执行相应功能代码,将此定时器重置,代码如下:

public float timer = 1.0f;
// Update is called once per frame
void Update() {
    timer -= Time.deltaTime;
    if (timer <= 0) {
        Debug.Log(string.Format("Timer1 is up !!! time=${0}", Time.time));
        timer = 1.0f;
    }
}

2、利用协程

在协程中返回需要等待的时间,直接看代码便明白:

// Use this for initialization
void Start() {
    StartCoroutine(Timer());
}
IEnumerator Timer() {
    while (true) {
        yield return new WaitForSeconds(1.0f);
        Debug.Log(string.Format("Timer2 is up !!! time=${0}", Time.time));
    }
}

3、延迟调用

使用 MonoBehaviour.Invoke,两个参数,分别是要调用的方法名和延时调用的时间。代码如下:

// Use this for initialization
void Start() {
    Invoke("Timer", 1.0f);
}
void Timer() {
    Debug.Log(string.Format("Timer3 is up !!! time=${0}", Time.time));
    Invoke("Timer", 1.0f);
}

补充:unity3D 实现一个时分秒的计时器:格式为00:00:00

简单粗暴,上代码。

public class Clock : MonoBehaviour {
    public Text m_ClockText;
    private float m_Timer;
    private int m_Hour;//时
    private int m_Minute;//分
    private int m_Second;//秒
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
        m_Timer += Time.deltaTime;
        m_Second = (int)m_Timer;     
        if (m_Second > 59.0f)
        {
            m_Second = (int)(m_Timer - (m_Minute * 60));
        }
        m_Minute = (int)(m_Timer / 60);       
        if (m_Minute > 59.0f)
        {
            m_Minute = (int)(m_Minute - (m_Hour * 60));
        }
        m_Hour = m_Minute / 60;
        if (m_Hour >= 24.0f)
        {
            m_Timer = 0;
        }
        m_ClockText.text = string.Format("{0:d2}:{1:d2}:{2:d2}", m_Hour,m_Minute,m_Second); 
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持悠悠之家。如有错误或未考虑完全的地方,望不吝赐教。

点赞(96)

评论列表共有 0 条评论

立即
投稿
返回
顶部