1. 最簡單實用的寫法。按下 Esc 按鍵後,瞬間關閉遊戲。如下程式碼:
if(Input.GetKeyDown("escape")){
Application.Quit();
}
版本二可看這篇文章(多出按鈕&重置):Unity 入門教學: (手機可用) 結束遊戲(鍵盤ESC & 按鈕)、重置遊戲
2. 比較華麗的效果。按下 Esc 按鍵後,會彈出是否結束遊戲的詢問視窗 (而且會淡出顯示)。
程式碼如下:
using UnityEngine;
using System.Collections;
public class QuitGame : MonoBehaviour
{
// public
public int windowWidth = 400;
public int windowHight = 150;
// private
Rect windowRect ;
int windowSwitch = 0;
float alpha = 0;
void GUIAlphaColor_0_To_1 ()
{
if (alpha < 1) {
alpha += Time.deltaTime;
GUI.color = new Color (1, 1, 1, alpha);
}
}
// Init
void Awake ()
{
windowRect = new Rect (
(Screen.width - windowWidth) / 2,
(Screen.height - windowHight) / 2,
windowWidth,
windowHight);
}
void Update ()
{
if (Input.GetKeyDown ("escape")) {
windowSwitch = 1;
alpha = 0; // Init Window Alpha Color
}
}
void OnGUI ()
{
if (windowSwitch == 1) {
GUIAlphaColor_0_To_1 ();
windowRect = GUI.Window (0, windowRect, QuitWindow, "Quit Window");
}
}
void QuitWindow (int windowID)
{
GUI.Label (new Rect (100, 50, 300, 30), "Are you sure you want to quit game ?");
if (GUI.Button (new Rect (80, 110, 100, 20), "Quit")) {
Application.Quit ();
}
if (GUI.Button (new Rect (220, 110, 100, 20), "Cancel")) {
windowSwitch = 0;
}
GUI.DragWindow ();
}
}
留言列表