要素理解
- timeScale(Float,默认值为1)能够影响时间流速,置0可使时间暂停
- 查阅官网文档 Time.timeScale 中可以发现对于timeScale描述中要求暂停物体的函数中所有相关变量与帧无关,而当在realtimeSinceStartup中可以对所有受时间类影响的物体产生影响。
- 帧无关即指与实际时间无关,Unity中时间计算是由相关变量决定的,很多文章中直接使用“timeScale适用范围与时间相关的变量无效”的描述不够准确。
代码
暂停UI代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class uiController : MonoBehaviour
{
[SerializeField]Transform UIPanel;
bool isPaused = false;
// Start is called before the first frame update
void Start()
{
UIPanel.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape) && !isPaused)
{
Pause();
Debug.Log("GetPause");
}
else if(Input.GetKeyDown(KeyCode.Escape)&& isPaused)
{
unPause();
Debug.Log("GetUnpause");
}
}
private void Pause()
{
isPaused = true;
UIPanel.gameObject.SetActive(true);
Time.timeScale = 0f;
}
private void unPause()
{
isPaused = false;
UIPanel.gameObject.SetActive(false);
Time.timeScale = 1f;
}
}
以下为测试场景中的移动物体脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moveSquare : MonoBehaviour
{
private Vector2 SelfPos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
SelfPos = this.gameObject.transform.position;
SelfPos.x += Time.deltaTime;//此处进行测试
this.gameObject.transform.position = SelfPos;
}
}
若更改代码为
SelfPos.x += 0.02f;
物体将不会收到影响。
分析理解
- 上述代码中修改前与Time类中变量相关,可以理解为deltaTime中包含timeScale作为系数,因此在每帧刷新的过程中SelfPos不会累加,而当修改为常值后,update仍旧持续工作,而对于物体位移可以视为SelfPos.x(末位置)=SelfPos.x(初始位置)+frame*0.02f,便是与帧(实际时间)相关。