1 前言
1)场景切换
场景切换可以使用 SceneManager 的 LoadScene 和 LoadSceneAsync 方法,如下:
public static void LoadScene(string sceneName)
public static void LoadScene(int sceneBuildIndex)
public static AsyncOperation LoadSceneAsync(string sceneName)
public static AsyncOperation LoadSceneAsync(int sceneBuildIndex)
2)退出全屏
退出全屏可以使用 Screen 的 fullScreen 属性,如下:
if (Input.GetKeyDown(KeyCode.Escape)) {
fullScreen = !fullScreen;
Screen.fullScreen = fullScreen;
}
3)退出游戏
退出游戏可以使用 Application 的 Quit 方法,如下:
if (Input.GetKeyDown(KeyCode.Q)) {
Application.Quit();
}
2 应用
2.1 场景一
1)游戏对象
2)游戏界面
3)脚本组件
SceneController1.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SceneController1 : MonoBehaviour {
private bool fullScreen = true;
private void Start () {
Button jumpBtn = transform.GetComponent<Button>();
jumpBtn.onClick.AddListener(OnClickJump);
}
private void Update() {
if (Input.GetKeyDown(KeyCode.Escape)) { // 全屏与恢复
fullScreen = !fullScreen;
Screen.fullScreen = fullScreen;
}
if (Input.GetKeyDown(KeyCode.Q)) { // 退出游戏
Application.Quit();
}
}
private void OnClickJump() { // 切换场景
SceneManager.LoadScene("Scene2");
// SceneManager.LoadSceneAsync("Scene2");
}
}
说明: SceneController1 脚本组件挂在 Button 控件上。
2.2 场景二
1)游戏对象
2)游戏界面
3)脚本组件
SceneController2.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SceneController2 : MonoBehaviour {
private bool fullScreen = true;
private void Start () {
Button jumpBtn = transform.GetComponent<Button>();
jumpBtn.onClick.AddListener(OnClickJump);
}
private void Update() {
if (Input.GetKeyDown(KeyCode.Escape)) { // 全屏与恢复
fullScreen = !fullScreen;
Screen.fullScreen = fullScreen;
}
if (Input.GetKeyDown(KeyCode.Q)) { // 退出游戏
Application.Quit();
}
}
private void OnClickJump() { // 切换场景
SceneManager.LoadScene("Scene1");
// SceneManager.LoadSceneAsync("Scene1");
}
}
说明: SceneController2 脚本组件挂在 Button 控件上。
2.3 场景切换
依次选择【File→Build Settings】(或按 Ctrl + Shift + B 快捷键),将 Scene1 和 Scene2 拖拽到 Scenes In Build 框中,如下:
运行效果如下: