当前位置:网站首页>【Unity3D】场景切换、退出全屏、退出游戏
【Unity3D】场景切换、退出全屏、退出游戏
2022-07-29 11:31:00 【little_fat_sheep】
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 框中,如下:

运行效果如下:

边栏推荐
猜你喜欢
随机推荐
ES6 arrow function this points to
2022 latest WiFi master applet independent version 3.0.8
TCP and UDP
什么是 Kubernetes 自定义资源定义 (CRD)?
面试官培训课件(非常实用的企业内训课件)
Regular expression matching URL
golang 实现文件上传下载
【无标题】
解决idea在debug模式下变得非常慢的问题
[SwiftUI 开发] @State @Binding @ObservedObject @EnvironmentObject
Niuke net brush questions
自采集在线电脑壁纸php源码v2.0自适应端
一键搭建博客:如何使用WordPress插件搭建专属博客
MyCat中间件高可用、读写分离、分片、主从切换、ER分片
Talk about the establishment of performance testing environment
INVALID_ ARGUMENT : Invalid rank for input: modelInput Got: 3 Expected: 4 Please fix either the input
共建共享数字世界的根:阿里云打造全面的云原生开源生态
KRYSTAL:审计数据中基于知识图的战术攻击发现框架
LeetCode_ 278_ First wrong version
QML(二):设置自定义窗体








