Unity3D时间类Time和DateTime的用法

系列文章目录

Unity知识点



大家好,我是心疼你的一切,不定时更新Unity开发技巧,觉得有用记得一键三连哦。

前言

只要是用到时间,日期都少不了用到时间类DataTime,但是DataTime和Time有什么区别呢?
下面就来写一下他们的区别


提示:以下是本篇文章正文内容,下面案例可供参考

一、Time和DataTime的区别

1-1、命名空间不同

Time 是在 using UnityEngine; 命名空间下面
DataTime 是在 using System; 命名空间下面

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

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

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

二、Time和DataTime的使用

2-1、Time类

在这里插入图片描述
图中,小红旗标识的为只读值,紫色标注的为可读可写

2-2、代码解释如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class TimeScript : MonoBehaviour
{
    // Start is called before the first frame update
    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的运行中获取与时间相关的信息。

2-3、DataTime类

在这里插入图片描述
红色小旗代表只读,蓝色为方法

2-4、代码解释如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataTimeScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(DateTime.Now);//当前本地时间 (年月日时分秒) 
        Debug.Log(DateTime.UtcNow);//当前世界时间 (年月日时分秒) 
        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));//后一天时间  
        Debug.Log(DateTime.Now.Date);//当前零点时间  00:00:00
        Debug.Log(DateTime.Compare(DateTime.Now, DateTime.Now));//时间比较
        Debug.Log(DateTime.DaysInMonth(2023, 12));//获取某年某月的天数
        Debug.Log(DateTime.IsLeapYear(2023));//判断是否是闰年
        Debug.Log(DateTime.Parse("2023年12月19日 16:04:42"));//格式化字符串
        Debug.Log(DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified));//指定格式

        //实例化DateTime类
        DateTime testTime = new DateTime(2023, 12, 19);
        testTime.ToLocalTime();
        Debug.Log(testTime.ToLocalTime());//本地时间
        Debug.Log(testTime.DayOfWeek);//返回星期的数值
        Debug.Log(testTime.Date);//获取日期
        Debug.Log(testTime.AddDays(1));//添加天数

    }
}

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

三、实际应用

3-1、Time类测试性能代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Time_ : 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 < 1000; i++)
        {
            num += 5;
        }
    }

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

3-2、运行结果如下:

在这里插入图片描述

3-3、Tiem还能控制游戏的加速,减速,暂停

加速: Time.timeScale = 2;
减速: Time.timeScale = 0.5;
暂停: Time.timeScale = 0;

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

代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataTime_ : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        DateTime dt1 = new DateTime(2023, 12, 19);
        DateTime dt2 = new DateTime(2024, 1, 1);
        TimeSpan span = dt2.Subtract(dt1);
        Debug.Log("天数差:"+span.Days);                        //返回天数差
        Debug.Log("天数差中的小时数:" + span.Hours);          //返回天数差中的小时数
        Debug.Log("天数差中的秒数:" + span.Seconds);        //返回天数差中的秒数
        Debug.Log("总秒数:"+span.TotalSeconds);            //返回开始时间到结束时间的总秒数
    }

}

3-5、运行结果如下:

在这里插入图片描述

3-6、DataTime类计算距离0点的时间

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataTime_night : MonoBehaviour
{
    // Start is called before the first frame update
    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));    
    }

}

3-7、运行结果

在这里插入图片描述

3-8、DataTime类的格式化输出

代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DataTimeFunction : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //DateTime详解
        DateTime dt = DateTime.Now;
        dt.GetDateTimeFormats('s')[0].ToString();//2023-12-19T14:06:25 
        dt.GetDateTimeFormats('t')[0].ToString();//14:06 
        dt.GetDateTimeFormats('y')[0].ToString();//2023年12月 
        dt.GetDateTimeFormats('D')[0].ToString();//2023年12月19日 
        dt.GetDateTimeFormats('D')[1].ToString();//2023 12 19 
        dt.GetDateTimeFormats('D')[2].ToString();//星期二 2023 12 19 
        dt.GetDateTimeFormats('D')[3].ToString();//星期二 2023年12月19日 
        dt.GetDateTimeFormats('M')[0].ToString();//12月19日 
        dt.GetDateTimeFormats('f')[0].ToString();//2023年12月19日 14:06 
        dt.GetDateTimeFormats('g')[0].ToString();//2023-12-19 14:06 
        dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2023 14:06:25 GMT

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

        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"));//秒

    }

}

3-9、运行结果

在这里插入图片描述

3-10、DataTime制作进度条

代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DataTimeSlider : 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开发技巧,觉得有用记得一键三连哦。
防止后面忘记,所以记录一下
有更详细的大佬文章:https://itmonon.blog.csdn.net/article/details/120267214?spm=1001.2014.3001.5502

  • 21
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心疼你的一切

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值