unity3D 点击按钮暂停和继续游戏

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.UI;
 5 
 6 public class CanvasSitting : MonoBehaviour
 7 {
 8     public GameObject SettingPanel;     //设置面板
 9     public bool isShow;                 //是否显示
10     public GameObject ControlButton;    //暂停/继续游戏的按钮
11     public Text BtnTitle;               //按钮显示的文字
12     public bool BtnState = false;       //暂停游戏按钮的状态
13 
14     void Start()
15     {
16         //寻找组件,注册点击事件
17         ControlButton.GetComponent<Button>().onClick.AddListener(ControlTime);
18         
19     }
20 
21     void Update()
22     {
23         SettingMenu();
24     }
25 
26     //设置面板
27     public void SettingMenu()
28     {
29         if (Input.GetKeyDown(KeyCode.Escape))
30         {
31             isShow = !isShow;
32             SettingPanel.gameObject.SetActive(isShow);
33         }
34     }
35 
36     //暂停和继续游戏
37     public void ControlTime()
38     {
39         //如果点击了
40         if (BtnState)
41         {
42             BtnState = false;
43             BtnTitle.text = "暂停游戏";
44             //将时间设置为0,画面会停止运动,慢动作可以设置为0.5f
45             Time.timeScale = 1f;
46         }
47         else
48         {
49             BtnState = true;
50             BtnTitle.text = "继续游戏";
51             //将时间设置为0,画面会停止运动,慢动作可以设置为0.5f
52             Time.timeScale = 0f;
53         }
54     }
55 }

说明:

将代码挂载到画布上,

将对应的游戏对象拖拽到代码公开变量上

实现两个功能:

①ESC按下显示设置面板,再按ESC隐藏面板

②点击面板上的按钮暂停游戏,在点击按钮继续游戏

效果

posted @ 2021-05-07 21:20  伊凡晴天  阅读(3083)  评论(0编辑  收藏  举报