Unity常用类—Time类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity常用类—Time类相关的知识,希望对你有一定的参考价值。

参考技术A realtimeSinceStartup:   程序实际运行的时间,从按下运行键开始计算以秒计算,该时不受暂停的影响,当游戏暂停后,该时间依旧在后台运行,根据硬件的不同,时间也会有差异

time:  此帧开始的时间这是游戏开始后以秒为单位的时间,为游戏运行的时间,不是每帧的时间

timeScale: 游戏的时间缩放,当该值越小时,整个场景的游戏物体的运行就会变慢,默认为1,当该值为0时,会暂停整个游戏

deltaTime : 当前帧与上一帧间隔所花费的时间,每一秒大概执行50-60帧,每一帧大概为0.02s

smoothDeltaTime: 平滑的Time.deltatime

fixedDeltaTime: 执行物理和其他固定帧速率更新的时间间隔(以秒为单位)fixedDeltaTime间隔是相对于受timeScale影响的游戏内时间。

fixedTime: 在fixedUpdate或者Update中以大概0.02s一帧的间隔进行更新,游戏开始运行的时间

fixedUnscaledDeltaTime: 从最后一个固定帧到当前固定帧的时间间隔,不受TimeScale的影响

frameCount: 游戏运行的总帧数,在Awake函数之后执行

timeSinceLevelLoad: 加载新场景后游戏以秒计运行的时间,加载新场景后会重置时间,且重新计算

Unity3D日常开发时间类Time和DateTime的使用

推荐阅读

  大家好,我是佛系工程师☆恬静的小魔龙☆,不定时更新Unity开发技巧,觉得有用记得一键三连哦。

一、前言

凡是用到时间,日期的都免不了要用到时间类DateTime,那么DateTime类跟Time类又有啥区别呢。

DateTime类的函数以及属性怎么用呢。

这一篇文章就将这些知识拿捏的明明白白。

二、Time和DateTime的区别

首先,来看一下Time和DateTime类的区别。

Time类是在 using UnityEngine; 命名空间下。
DateTime类是在 using System; 命名空间下。

从命名空间就可以看出来,Time类是Unity自带的时间类,而DateTime类是C#语言下的时间类。

Time类主要是保存Unity里面一系列和时间相关的数据,比如Time.time表示从游戏开始到现在的时间,会随着游戏暂停而停止,Time.deltaTime 表示从上一帧到当前帧时间,以秒为单位,又称增量时间。

而DateTime类主要是获取时间日期等相关的数据,比如DateTime.Now表示获取当前时间,DateTime.DaysInMonth(2007, 8)表示计算某年某月的天数。

三、Time和DateTime的使用

Time时间类


图中,小红旗标识的为只读值,紫色标注的为可读可写。

代码演示:

using UnityEngine;

public class TestTime : MonoBehaviour

    void Start()
    
        Debug.Log(Time.time);                   //表示从游戏运行到现在的时间,会随着游戏的暂停而停止计算。
        Debug.Log(Time.deltaTime);              //表示从上一帧到当前帧的时间,以秒为单位。
        Debug.Log(Time.unscaledDeltaTime);      //不考虑timescale时候与deltaTime相同,若timescale被设置,则无效。
        Debug.Log(Time.timeSinceLevelLoad);     //表示从当前Scene开始到目前为止的时间,也会随着暂停操作而停止。
        Debug.Log(Time.unscaledTime);           //不考虑timescale时候与time相同,若timescale被设置,则无效。
        Debug.Log(Time.fixedDeltaTime);         //表示以秒计间隔,在物理和其他固定帧率进行更新,在Edit->ProjectSettings->Time的Fixed Timestep可以自行设置。
        Debug.Log(Time.realtimeSinceStartup);   //表示自游戏开始后的总时间,即使暂停也会不断的增加。
        Debug.Log(Time.frameCount);             //总帧数
        Debug.Log(Time.fixedTime);              //表示以秒计游戏开始的时间,固定时间以定期间隔更新(相当于fixedDeltaTime)直到达到time属性。
        Debug.Log(Time.smoothDeltaTime);        //表示一个平稳的deltaTime,根据前 N帧的时间加权平均的值。
        Debug.Log(Time.timeScale);              //时间缩放,默认值为1,若设置<1,表示时间减慢,若设置>1,表示时间加快,可以用来加速和减速游戏,非常有用。
        Debug.Log(Time.captureFramerate);       //表示设置每秒的帧率,然后不考虑真实时间。
    

Time类主要作用就是为了从Unity的运行中获取与时间相关的信息。

比如Time.time表示从游戏运行到现在的时间,Time.deltaTime表示从上一帧到当前帧的时间,以秒为单位,通常移动的代码会用Time.deltaTime做平滑处理,让每一帧移动的距离都是合理的。

DateTime类


图中,小红旗标识的为只读值,蓝色为函数。

代码演示:

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

    void Start()
    
        Debug.Log(DateTime.Now);//当前本地时间 (年月日时分秒) -- 04/08/2020 14:06:48
        Debug.Log(DateTime.UtcNow);//当前世界时间 (年月日时分秒) -- 04/08/2020 06:08:58
        Debug.Log(DateTime.Now.Year);//当前时间 (年)
        Debug.Log(DateTime.Now.Month);//当前时间 (月)
        Debug.Log(DateTime.Now.Day);//当前时间 (日)
        Debug.Log(DateTime.Now.Hour);//当前时间 (时)
        Debug.Log(DateTime.Now.Minute);//当前时间 (分)
        Debug.Log(DateTime.Now.Second);//当前时间 (秒)
        Debug.Log(DateTime.Now.AddDays(1));//后一天时间  04/09/2020 14:06:48
        Debug.Log(DateTime.Now.Date);//当前零点时间  00:00:00
        Debug.Log(DateTime.Compare(DateTime.Now, DateTime.Now));//时间比较
        Debug.Log(DateTime.DaysInMonth(2021, 9));//获取某年某月的天数
        Debug.Log(DateTime.IsLeapYear(2021));//判断是否是闰年
        Debug.Log(DateTime.Parse("2021年9月13日 16:04:42"));//格式化字符串
        Debug.Log(DateTime.SpecifyKind(DateTime.Now,DateTimeKind.Unspecified));//指定格式
        
        //实例化DateTime类
        DateTime testTime = new DateTime(2021,9,13);
        testTime.ToLocalTime();
        Debug.Log(testTime.ToLocalTime());//本地时间
        Debug.Log(testTime.DayOfWeek);//返回星期的数值
        Debug.Log(testTime.Date);//获取日期
        Debug.Log(testTime.AddDays(1));//添加天数
    

DateTime时间类更多的是对日期时间的获取与操作。

比如获取当前时间DateTime.Now,获取某年某月的天数DaysInMonth(2021, 9))等。

下面,就介绍一下Time和DateTime的实际应用。

四、应用实例

4-1、Time类测试函数的性能

代码:

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

    void Start()
    
        //Time.realtimeSinceStartup: 表示自游戏开始后的总时间,即使暂停也会不断的增加。

        float time_1 = Time.realtimeSinceStartup;
        for (int i = 0; i < 10; i++)
        
            Function_1();
        
        float time_2 = Time.realtimeSinceStartup;
        Debug.Log("函数Function_1所用时间:" + (time_2 - time_1));

        float time_3 = Time.realtimeSinceStartup;
        for (int i = 0; i < 10; i++)
        
            Function_2();
        
        float time_4 = Time.realtimeSinceStartup;
        Debug.Log("函数Function_2所用时间:" + (time_4 - time_3));
    

    private void Function_1()
    
        int num = 1;
        for (int i = 0; i < 100; i++)
        
            num += 5;
        
    

    private void Function_2()
    
        int num = 1;
        for (int i = 0; i < 100; i++)
        
            num -= 5;
        
    

运行结果:

4-2、Time类控制物体移动

代码:

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

    public GameObject Cube;

    void Update()
    
        Cube.transform.Translate(Vector3.forward * Time.deltaTime * 30);
    

运行效果:

4-3、Time类控制对游戏进行加速、减速和暂停

这个主要使用Time类的timeScale属性进行控制:

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

	//暂停游戏
    public void Pause(bool isPause)
    
        if (isPause)
        
            Time.timeScale = 0;
            isPause = false;
        
        else
        
            Time.timeScale = 1;
            isPause = true;
        
    

4-4、DateTime类计算两个日期之间的天数差

代码:

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

    void Start()
    
        DateTime dt1 = new DateTime(2007, 8, 1);
        DateTime dt2 = new DateTime(2007, 8, 15);
        TimeSpan span = dt2.Subtract(dt1);
        Debug.Log(span.Days);           //返回天数差
        Debug.Log(span.Hours);          //返回天数差中的小时数
        Debug.Log(span.Seconds);        //返回天数差中的秒数
        Debug.Log(span.TotalSeconds);   //返回开始时间到结束时间的总秒数
    

运行结果:

4-5、DateTime类格式化输出

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

    void Start()
    
        DateTime dt = DateTime.Now;
        dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25 
        dt.GetDateTimeFormats('t')[0].ToString();//14:06 
        dt.GetDateTimeFormats('y')[0].ToString();//2005年11月 
        dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日 
        dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05 
        dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05 
        dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日 
        dt.GetDateTimeFormats('M')[0].ToString();//11月5日 
        dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06 
        dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06 
        dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT

        Debug.Log(dt.ToString("d"));//短日期:2021/9/13
        Debug.Log(dt.ToString("D"));//长日期:2021年9月13日
        Debug.Log(dt.ToString("f"));//完整短日期/时间:2021年9月13日 17:17
        Debug.Log(dt.ToString("F"));//完整长日期/时间:2021年9月13日 17:17:07
        Debug.Log(dt.ToString("g"));//常规短日期/时间:2021/9/13 17:17
        Debug.Log(dt.ToString("G"));//常规长日期/时间:2021/9/13 17:17:07
        Debug.Log(dt.ToString("R"));//日期时间:Mon, 13 Sep 2021 17:17:07 GMT
        Debug.Log(dt.ToString("s"));//可排序日期:2021-09-13T17:17:07
        Debug.Log(dt.ToString("t"));//短时间:17:17
        Debug.Log(dt.ToString("T"));//长时间:17:17:07
        Debug.Log(dt.ToString("u"));//通用可排序日期/时间:2021-09-13 17:17:07Z
        Debug.Log(dt.ToString("U"));//通用完整日期/时间:2021年9月13日 9:17:07
        Debug.Log(dt.ToString("Y"));//年月:2021年9月
        Debug.Log(dt.ToString("M"));//月日:9月13日

        Debug.Log(dt.ToString("yyyy"));//年
        Debug.Log(dt.ToString("MM"));//月
        Debug.Log(dt.ToString("dd"));//日
        Debug.Log(dt.ToString("hh"));//时
        Debug.Log(dt.ToString("mm"));//分
        Debug.Log(dt.ToString("ss"));//秒
    

运行结果:

4-6、DateTime类计算距离零点的时间

using System;
using UnityEngine;

public class TestTime : MonoBehaviour

    void Start()
    
        TimeSpan date;
        date = DateTime.Now.AddDays(1).Date - DateTime.Now;
        //距离零点时间
        Debug.Log(string.Format("0:D2:1:D2:2:D2", date.Hours, date.Minutes, date.Seconds));    
    

运行结果:

4-7、DateTime类制作时间进度条

代码:

using System;
using UnityEngine;
using UnityEngine.UI;

public class TestTime : MonoBehaviour

    public Text TextCurrentTime;
    public Slider Slider;
    private DateTime CurrentTime;
    private float sliderValueScale = 0.1f;
    private DateTime StartTime;
    private DateTime EndTime;
    private bool isPlay = true;

    void Start()
    
        StartTime= DateTime.Now;
        CurrentTime = StartTime;
        EndTime = DateTime.Now.AddSeconds(10);//增加10秒

        TimeSpan timeSpan = EndTime.Subtract(StartTime);
        double totalSeconds = timeSpan.TotalSeconds;//返回开始时间到结束时间的总秒数
        sliderValueScale = (float)(1 / totalSeconds);//返回slider播放的速度
    

    void Update()
    
        if (isPlay)
        
            if (CurrentTime >= EndTime)
            
                isPlay = false;
            
            CurrentTime = CurrentTime.AddSeconds(1 * Time.deltaTime);
            TextCurrentTime.text = CurrentTime.ToString();
            Slider.value += sliderValueScale * Time.deltaTime;
        
    

效果图:

以上是关于Unity常用类—Time类的主要内容,如果未能解决你的问题,请参考以下文章

Unity常用类—Transform类

使用Photon引擎进行unity网络游戏开发——Photon常用类介绍

java.time包常用类API学习记录

04Unity-常用核心类

Unity脚本常用类和类的函数

java常用类Time