Unity的C#编程教程_5_游戏的暂停和重启设置

Pause System

  • 可以下载一个官方的免费带动画的角色进行尝试,可以看得更直观
  • 希望达到目的:按下空格键,可以暂停游戏
  • 游戏里面的事件由 Time.timeScale 控制
  • 创建一个新的 C# Script,命名为 Pause
  • 将脚本挂载到 Main Camera 下面的组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pause : MonoBehaviour
{

    public bool gamePause;

    // Start is called before the first frame update
    void Start()
    {
        gamePause = false; // 监测状态,初始化的时候表示没有暂停
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && gamePause == false)
        {
            Time.timeScale = 0;
            // 默认值是 1,设置为 0.5f,则是把速度降低一半,设置为 0 则暂停
            // 设置为 5 则为 5 倍速
            gamePause = true;
        }

        else if (Input.GetKeyDown(KeyCode.Space) && gamePause == true)
        {
            Time.timeScale = 1;
            // 在暂停过程按下空格,恢复原速度
            gamePause = false;
        }
    }
}
Tags: