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隱藏面板
②點擊面板上的按鈕暫停游戲,在點擊按鈕繼續游戲
效果