unity3d之按秒倒计时

2020-11-13  本文已影响0人  Lee_5566
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,则在下一个更新周期调用方法。在这种情况下,直接调用函数会更好。

`

上一篇 下一篇

猜你喜欢

热点阅读