版本:Unity 6 (6000.0)
语言英语
  • C#

SceneManager.MoveGameObjectToScene

提出更改建议

成功!

感谢您帮助我们提升 Unity 文档的品质。虽然我们无法接受所有提交内容,但我们确实会阅读用户提出的每一条更改建议,并在合适的情况下进行更新。

关闭

提交失败

由于某些原因,您的更改建议无法提交。请在几分钟后<a>重试</a>。感谢您抽出时间帮助我们提升 Unity 文档的品质。

关闭

取消

声明

public static void MoveGameObjectToScene(GameObject go, SceneManagement.Scene scene);

参数

go 要移动的 GameObject。
scene 要移动到的场景。

说明

将一个 GameObject 从其当前场景移动到一个新的场景。

只能将根 GameObject 从一个场景移动到另一个场景。这意味着要移动的 GameObject 不能是其场景中任何其他 GameObject 的子项。它仅对移动到已加载场景(可添加)的 GameObject 有效。如果要加载单个场景,请务必对您要移动到新场景中的 GameObject 使用 DontDestroyOnLoad,否则 Unity 会在加载新场景时删除它。

// This script moves the GameObject you attach in the Inspector to a Scene you specify in the Inspector.
// Attach this script to an empty GameObject.
// Click on the GameObject, go to its Inspector and type the name of the Scene you would like to load in the Scene field.
// Attach the GameObject you would like to move to a new Scene in the "My Game Object" field

// Make sure your Scenes are in your build (File>Build Settings).

using System.Collections; using UnityEngine; using UnityEngine.SceneManagement;

public class Example : MonoBehaviour { // Type in the name of the Scene you would like to load in the Inspector public string m_Scene;

// Assign your GameObject you want to move Scene in the Inspector public GameObject m_MyGameObject;

void Update() { // Press the space key to add the Scene additively and move the GameObject to that Scene if (Input.GetKeyDown(KeyCode.Space)) { StartCoroutine(LoadYourAsyncScene()); } }

IEnumerator LoadYourAsyncScene() { // Set the current Scene to be able to unload it later Scene currentScene = SceneManager.GetActiveScene();

// The Application loads the Scene in the background at the same time as the current Scene. AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(m_Scene, LoadSceneMode.Additive);

// Wait until the last operation fully loads to return anything while (!asyncLoad.isDone) { yield return null; }

// Move the GameObject (you attach this in the Inspector) to the newly loaded Scene SceneManager.MoveGameObjectToScene(m_MyGameObject, SceneManager.GetSceneByName(m_Scene)); // Unload the previous Scene SceneManager.UnloadSceneAsync(currentScene); } }