target | 在加载新场景时不会销毁的对象。 |
在加载新场景时,不要销毁目标对象。
加载新场景会销毁所有当前场景对象。调用Object.DontDestroyOnLoad 以在场景加载期间保留对象。如果目标对象是组件或游戏对象,Unity 也会保留所有变换的子对象。Object.DontDestroyOnLoad 仅适用于根游戏对象或根游戏对象上的组件。Object.DontDestroyOnLoad 不返回值。
以下示例脚本使用Object.DontDestroyOnLoad。该示例具有scene1
,它从音频源开始播放背景音乐。当scene2
加载时,音乐会继续播放。使用按钮在场景之间切换。
要实现此示例,请创建两个新的场景,命名为scene1
和scene2
。打开scene1
并将SceneSwap.cs
脚本添加到一个空游戏对象中,并将其命名为Menu
。接下来,将DontDestroy.cs
添加到一个新的游戏对象中,并将其命名为BackgroundMusic
。将音频源添加到BackgroundMusic
中 - 添加组件 > 音频 > 音频源
- 并将音频剪辑导入您的项目。将音频剪辑分配给音频源的音频剪辑字段。创建一个标签,将其命名为music
,并将其添加到BackgroundMusic
中。切换到scene2
。再次将SceneSwap.cs
添加到一个新的游戏对象中,并将其命名为Menu
。保存项目。返回scene1
并从编辑器
运行项目。SceneSwap.cs
脚本
using UnityEngine; using UnityEngine.SceneManagement;
// Object.DontDestroyOnLoad example. // // Two scenes call each other. This happens when OnGUI button is clicked. // scene1 will load scene2; scene2 will load scene1. Both scenes have // the Menu GameObject with the SceneSwap.cs script attached. // // AudioSource plays an AudioClip as the game runs. This is on the // BackgroundMusic GameObject which has a music tag. The audio // starts in AudioSource.playOnAwake. The DontDestroy.cs script // is attached to BackgroundMusic.
public class SceneSwap : MonoBehaviour { private void OnGUI() { int xCenter = (Screen.width / 2); int yCenter = (Screen.height / 2); int width = 400; int height = 120;
GUIStyle fontSize = new GUIStyle(GUI.skin.GetStyle("button")); fontSize.fontSize = 32;
Scene scene = SceneManager.GetActiveScene();
if (scene.name == "scene1") { // Show a button to allow scene2 to be switched to. if (GUI.Button(new Rect(xCenter - width / 2, yCenter - height / 2, width, height), "Load second scene", fontSize)) { SceneManager.LoadScene("scene2"); } } else { // Show a button to allow scene1 to be returned to. if (GUI.Button(new Rect(xCenter - width / 2, yCenter - height / 2, width, height), "Return to first scene", fontSize)) { SceneManager.LoadScene("scene1"); } } } }
DontDestroy.cs
脚本
using System.Collections; using System.Collections.Generic; using UnityEngine;
// Object.DontDestroyOnLoad example. // // This script example manages the playing audio. The GameObject with the // "music" tag is the BackgroundMusic GameObject. The AudioSource has the // audio attached to the AudioClip.
public class DontDestroy : MonoBehaviour { void Awake() { GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
if (objs.Length > 1) { Destroy(this.gameObject); }
DontDestroyOnLoad(this.gameObject); } }