Unity 游戏退出 之 编辑状态下的游戏退出
1、Application.Quit:
1)功能简述
public static void Quit();
Quits the player application.
Quit is ignored in the editor. IMPORTANT: In most cases termination of application under iOS should be left at the user discretion. Consult Apple Technical Page qa1561 for further details.
2)使用举例
using UnityEngine;
using System.Collections;public class ExampleClass : MonoBehaviour {
void Update() {
if (Input.GetKey("escape"))
Application.Quit();
}
}
2、EditorApplication.isPlaying:
1)功能简述
public static bool isPlaying;
Is editor currently in play mode?
Setting isPlaying delays the result until after all script code has completed for this frame.See Also: isPaused, isPlayingOrWillChangePlaymode.
2)使用举例
// Simple editor Script that lets you save a scene while in play mode.
// WARNING: All Undo posibilities are lost after saving the scene.import UnityEditor;@MenuItem("Example/Save Scene while on play mode")
static function EditorPlaying() {
if(EditorApplication.isPlaying) {
var sceneName : String = EditorApplication.currentScene;
var path : String [] = sceneName.Split(char.Parse("/"));
path[path.Length -1] = "Temp_" + path[path.Length-1];
var tempScene = String.Join("/",path); EditorApplication.SaveScene(tempScene);
EditorApplication.isPaused = false;
EditorApplication.isPlaying = false;
FileUtil.DeleteFileOrDirectory(EditorApplication.currentScene);
FileUtil.MoveFileOrDirectory(tempScene, sceneName);
FileUtil.DeleteFileOrDirectory(tempScene);
EditorApplication.OpenScene(sceneName);
}
}
1、打开Unity,新建一个工程,具体如下图
2、在场景中,新建一个“Cube”,具体如下图
3、在工程中,新建一个脚本“QuitGame”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图
4、在“QuitGame”脚本上编辑代码,在Update函数中,当按下“Q”键时,如果是编辑状态使用“UnityEditor.EditorApplication.isPlaying = false;”退出,并打印;如果是正常下“Application.Quit();”退出,并打印,具体如下图
5、“QuitGame”脚本的具体内容如下:
using UnityEngine;
public class QuitGame : MonoBehaviour {
// Update is called once per frame
void Update () {
if(Input.GetKeyDown (KeyCode.Q)) {
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
Debug.Log ("编辑状态游戏退出");
#else
Application.Quit();
Debug.Log ("游戏退出"):
#endif
}
}
}
6、脚本编译正确,回到Unity界面,在场景中,新建一个“GameObject”,把脚本“QuitGame”赋给“GameObject”,具体如下图
7、运行场景,在游戏视图中,按下“Q”键,在编辑状态下,游戏也可以正常退出,并且控制台Console打印对应信息,具体如下图
8、到此,《Unity 游戏退出 之 编辑状态下的游戏退出》讲解结束,谢谢