Unity API详解——Time类

Time类是Unity中获取时间信息的接口类,只有静态属性。本博客介绍Time类的一些静态属性。

一、Time类静态属性

在Time类中,涉及的静态属性有realtimeSinceStartup、smoothDeltaTime和time属性,在介绍time属性时涉及了Time类的多个其他属性的使用。

1、reltimeSinceStartup属性:程序运行实时时间

(1)基本语法
public static float realtimeScienceStartup { get; }
(2)功能说明

此属性用于返回从游戏启动到现在已运行的实时时间(只读),以秒为单位。此属性通常可用Time.time代替使用,但realtimeSinceStartup的返回值不受timeScale属性变化的影响。

(3)代码实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RealtimeSinceStartup_test : MonoBehaviour
{
    public Rigidbody rg;
    void Start()
    {
        Debug.Log("Time.timeScale的默认时间: " + Time.timeScale);
        //观察刚体在timeScale变化前后的移动速度
        rg.velocity = Vector3.forward * 2.0f;
        Time.timeScale = 0.5f;
    }

    
    void Update()
    {
        Debug.Log("Time.timeScale的当前值: " + Time.timeScale);
        Debug.Log("Time.time:" + Time.time);
        Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);
    }

   void OnGUI()
   {
        if (GUI.Button(new Rect(10.0f, 10.0f,200.0f, 45.0f), "Time.timeScale = 0.5f"))
        {
            Time.timeScale = 0.5f;
        }
        if (GUI.Button(new Rect(10.0f,60.0f,200.0f,45.0f),"Time.timeScale = 1.0f"))
        {
            Time.timeScale = 1.0f;
        }
   }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这段代码中,首先声明了一个Rigidbody变量rg,并在Start方法中给刚体rg一个出事速度,然后再方法OnGUI中定义了两个Button用来控制Time.timeScale的值,最后再Update方法中分别打印出了Time.timeScaleTime.timeScaleTime.timeTime.realtimeSinceStartup的值

2、reltimeSinceStartup属性:程序运行实时时间

(1)基本语法
public static float smoothDeltaTime { get; }
(2)基本语法

此属性用于返回Time.deltaTime的平滑输出值(只读)。Time.smoothDeltaTimeTime.deltaTime的波幅震荡更平滑,通常Time.smoothDeltaTime的累加和比Time.deltaTime的累加稍微大些。Time.smoothDeltaTime主要用于在于在非FixedUpdate方法中需要平滑过渡的计算

(3)代码实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SmoothDeltaTime_test : MonoBehaviour
{
    float a = 0, b= 0;

    // Update is called once per frame
    void Update()
    {
        float t1, t2;
        t1 = Time.deltaTime;
        t2 = Time.smoothDeltaTime;
        Debug.Log("Time.deltaTime:" + t1);
        Debug.Log("Time.deltaTime:" + t2);
        a += t1;
        b += t2;
        Debug.Log("Time.deltaTime的累加和:" + a + "smoothDeltaTime的累加和:" + b);
    }
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

极客范儿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值