栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity3D实现游戏暂停

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity3D实现游戏暂停

Unity3D实现游戏暂停
  • 要素理解
  • 代码
  • 分析理解

要素理解
  • 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,便是与帧(实际时间)相关。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/900347.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号