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);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Prototype___/article/details/130983911