logo小熊博客
首页 fk标记语言示例 登录
目录
Unity 中的时间操作

一、获取当前时间

System.DateTime now = System.DateTime.Now;
Debug.Log("当前时间:" + now.ToString("yyyy-MM-dd HH:mm:ss"));
now.ToString("yyyy/MM/dd HH:mm:ss");
now.ToString("HH:mm"); // 只显示小时分钟

二、获取游戏运行时间

属性说明

Time.time

从游戏开始到现在经过的秒数(受暂停影响)

Time.realtimeSinceStartup

从游戏开始到现在的真实时间,不受暂停影响

Time.deltaTime

当前帧耗时(上一帧到当前帧的时间,秒)

Time.unscaledTime

忽略 Time.timeScale 的游戏时间

void Update()
{
    Debug.Log("游戏已运行:" + Time.time + " 秒");
    Debug.Log("这一帧耗时:" + Time.deltaTime + " 秒");
}

三、实现倒计时(常用方式)

方法1:用 Update() 手动递减

public float countDown = 5f;

void Update()
{
    if (countDown > 0)
    {
        countDown -= Time.deltaTime;
        Debug.Log("剩余时间:" + Mathf.Ceil(countDown));
    }
    else
    {
        Debug.Log("倒计时结束");
    }
}

方法2:使用协程 StartCoroutine

IEnumerator CountDown(float seconds)
{
    while (seconds > 0)
    {
        Debug.Log("剩余时间:" + Mathf.Ceil(seconds));
        yield return new WaitForSeconds(1f);
        seconds--;
    }

    Debug.Log("倒计时结束!");
}

void Start()
{
    StartCoroutine(CountDown(5));
}

四、延迟执行方法

void Start()
{
    Invoke("DoSomething", 3f); // 延迟3秒执行 DoSomething
}

void DoSomething()
{
    Debug.Log("3秒后执行的方法");
}
场景使用方式

倒计时(不精准)

Update() + Time.deltaTime

精准倒计时

StartCoroutine() + WaitForSeconds

获取当前日期时间

System.DateTime.Now

暂停游戏

Time.timeScale = 0f

延迟执行方法

Invoke() 或协程

运行时长

Time.timeTime.realtimeSinceStartup

上一篇:unity的协程
下一篇:Unity中的单例模式
请我喝奶茶!
赞赏码
手机扫码访问
手机访问