一、获取当前时间
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.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秒后执行的方法");
}
| 场景 | 使用方式 |
|---|---|
倒计时(不精准) | |
精准倒计时 | |
获取当前日期时间 | |
暂停游戏 | |
延迟执行方法 | |
运行时长 | |



