美文网首页
unity3d之按秒倒计时

unity3d之按秒倒计时

作者: Lee_5566 | 来源:发表于2020-11-13 10:20 被阅读0次
image.png

按秒倒计时

自定义变量计时

在程序中定义变量来累计时间。

实例代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class textTimer : MonoBehaviour
{
    // Start is called before the first frame update
    public int second = 120;
    private float startTime = 0;
    public Text mText;

    void Start()
    {
        mText = this.GetComponent<Text>();
        startTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        if ((Time.time - startTime) >= 1)
        {
            startTime = Time.time;
            second--;

            if (second <= 10) 
            {
                mText.color = Color.red;
            }
            mText.text = string.Format("{0:d2}:{1:d2}", second / 60, second % 60);
             
        }
    }
}

执行效果:


image.png

使用定时

MonoBehaviour.InvokeRepeating

在 time 秒后调用 methodName 方法,然后每 repeatRate 秒调用一次。

注意:如果将时间刻度设置为 0,该函数不起作用。

常常和MonoBehaviour.CancelInvoke一起使用。

MonoBehaviour.CancelInvoke

取消该 MonoBehaviour 上的所有 Invoke 调用。

MonoBehaviour.Invoke

在 time 秒后调用 methodName 方法。

如果时间设置为 0,则在下一个更新周期调用方法。在这种情况下,直接调用函数会更好。

`

相关文章

网友评论

      本文标题:unity3d之按秒倒计时

      本文链接:https://www.haomeiwen.com/subject/ssjybktx.html