Object.DontDestroyOnLoad

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

参数

target更换场景时不销毁的对象。

描述

加载新场景时,不自动销毁对象 /target/。

When loading a new level, all objects in the scene are destroyed, then the objects in the new level are loaded. In order to preserve an object during level loading call DontDestroyOnLoad on it. If the object is a component or game object then its entire transform hierarchy will not be destroyed either.

Note: DontDestroyOnLoad does not return a value. It is also intended to have its argument changed. The typeof operator makes this change if it is needed.

调用 DontDestroyOnLoad 可使对象存在于所有场景中。在下面的示例中,有两个场景 - ExampleScript1 和 /ExampleScript2/。一个包含立方体,另一个包含球体。第一个场景中的 DontDestroyOnLoad 函数连接到一个圆柱体。该圆柱体在 Awake 中加载。按下 ExampleScript1 按钮时,将关闭 ExampleScript1 并加载 ExampleScript2。ExampleScript1 中的圆柱体将复制到 ExampleScript2。按下 ExampleScript2 按钮时,将关闭 ExampleScript2,并重新加载 ExampleScript1。该场景将始终包含此圆柱体。该圆柱体由 DontDestroyOnLoad 函数进行管理。

ExampleScript1:

// Connected to the Cube and includes a DontDestroyOnLoad()
// LoadScene() is called by the first  script and switches to the second.

using UnityEngine; using UnityEngine.SceneManagement;

public class ExampleScript1 : MonoBehaviour { private static bool created = false;

void Awake() { if (!created) { DontDestroyOnLoad(this.gameObject); created = true; Debug.Log("Awake: " + this.gameObject); } }

public void LoadScene() { if (SceneManager.GetActiveScene().name == "scene1") { SceneManager.LoadScene("scene2", LoadSceneMode.Single); } } }

ExampleScript2:

// Connected to the Cube and includes a DontDestroyOnLoad()
// LoadScene() is called by the second script and loads the first.

using UnityEngine; using UnityEngine.SceneManagement;

public class ExampleScript2 : MonoBehaviour { public void LoadScene() { if (SceneManager.GetActiveScene().name == "scene2") { SceneManager.LoadScene("scene1", LoadSceneMode.Single); } } }