Version: 2022.1

Object.DontDestroyOnLoad

切换到手册
public static void DontDestroyOnLoad (Object target);

参数

target Scene 改变时不销毁的 Object。

描述

在加载新的 Scene 时,请勿销毁 Object。

The load of a new Scene destroys all current Scene objects. Call Object.DontDestroyOnLoad to preserve an Object during scene loading. If the target Object is a component or GameObject, Unity also preserves all of the Transform’s children. Object.DontDestroyOnLoad only works for root GameObjects or components on root GameObjects. Object.DontDestroyOnLoad does not return a value.

以下示例脚本便使用了 Object.DontDestroyOnLoad。该示例中的 scene1 开始播放来自 AudioSource 的背景音乐。在 scene2 加载时,音乐继续播放。使用一个按钮可以切换场景。

要实现此示例,我们创建两个新的 Scene,分别名为 scene1 和 /scene2/。打开 /scene1/,将 SceneSwap.cs 脚本添加到空的 GameObject,然后将其命名为 /Menu/。接着,将 DontDestroy.cs 添加到新的 GameObject,然后将其命名为 /BackgroundMusic/。将一个 AudioSource 添加到 BackgroundMusic - Add Component > Audio > Audio Source - 并将一个 AudioClip 导入项目中。将 AudioClip 分配给 AudioSourceAudioClip 字段。创建一个命名为 music 的标签,然后将其添加到 /BackgroundMusic/。切换到 /scene2/。同样,将 SceneSwap.cs 添加到新的 GameObject,然后将其命名为 scene1。保存项目。返回到 scene1 并从 Editor 中运行项目。

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); } }