【发布时间】:2021-03-19 05:14:49
【问题描述】:
当我单击按钮时,我会加载一个新场景并实例化预制件。 问题是:预制件是在旧场景而不是新场景中创建的 如何在下一个场景或特定场景中实例化预制件?
【问题讨论】:
-
加载新场景时是否正在卸载当前场景?
当我单击按钮时,我会加载一个新场景并实例化预制件。 问题是:预制件是在旧场景而不是新场景中创建的 如何在下一个场景或特定场景中实例化预制件?
【问题讨论】:
实例化预制件并使用SceneManager.MoveGameObjectToScene 将对象从旧场景移动到新场景。来自文档:
MoveGameObjectToScene
将游戏对象从其当前场景移动到新场景。
您只能将根 GameObjects 从一个场景移动到另一个场景。这意味着 要移动的游戏对象不能是其中任何其他游戏对象的子对象 场景。这仅适用于被移动到场景的游戏对象 已经加载(添加剂)。如果要加载单个场景,请制作 确保在要移动的游戏对象上使用 DontDestroyOnLoad 到新场景,否则 Unity 会在加载新场景时将其删除。
还有例子:
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);
}
}
【讨论】:
使用PrefabUtility.InstantiatePrefab。它允许指定目标场景。
【讨论】:
两种选择:
【讨论】: