计时器的三种用法

孔乙己:“茴字有三种写法,你知道吗?”
我:“不知道.”
第一种:使用变量在Update中计时,也是各种书中最常见的方法。

public class TestTimer : MonoBehaviour {

    private float lastTime;
    private float curTime;

    void Start () {
        lastTime = Time.time;
    }

    void Update () {
        curTime = Time.time;
        if (curTime - lastTime >= 3)
        {
            Debug.Log("work");
            lastTime = curTime;
           }
    }
}

第二种:使用协程Coroutine

public class TestTimer : MonoBehaviour {

    void Start () {
        StartCoroutine(Do()); // 开启协程
    }

    IEnumerator Do()
    {
        while (true) // 还需另外设置跳出循环的条件
        {
            yield return new WaitForSeconds(3.0f);
            Debug.Log("work");
        }
    }
}

第三种:使用InvokeRepeating

public class TestTimer : MonoBehaviour {

    void Start () {
        InvokeRepeating("Do", 3.0f, 3.0f);
    }

    void Do()
    {
        Debug.Log("work");
    }
}


感谢霍丽雪特博主!

作者:霍莉雪特
来源:CSDN
原文:https://blog.csdn.net/qq_18995513/article/details/51941417
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/hennysky/article/details/85316676