当我点击按钮时,我加载一个新场景并实例化预制。 问题是:预制件是在旧场景中创建的,而不是新场景 如何在下一个场景或特定场景中实例化预制?
答案 0 :(得分:1)
实例化预制件并使用SceneManager.MoveGameObjectToScene
将对象从旧场景移动到新场景。来自文档:
<强> MoveGameObjectToScene 强>
将GameObject从当前场景移动到新场景。
您只能将根游戏对象从一个场景移动到另一个场景。这意味着 要移动的GameObject不能是其中任何其他GameObject的子对象 现场。这仅适用于移动到场景的GameObjects 已加载(添加剂)。如果你想加载单个场景,请制作 一定要在你想要移动的GameObject上使用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);
}
}
答案 1 :(得分:0)
两个选项:
答案 2 :(得分:0)
使用PrefabUtility.InstantiatePrefab。它允许指定目标场景。