首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在(另一个)场景中实例化预制件

在(另一个)场景中实例化预制件
EN

Stack Overflow用户
提问于 2018-05-02 23:42:01
回答 3查看 4.7K关注 0票数 1

当我点击按钮,我加载一个新的场景和实例化预制件。问题是:预制件是在旧场景中创建的,而不是新场景,如何在下一个场景或特定场景中实例化预制件?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-05-03 00:51:11

实例化预制件并使用SceneManager.MoveGameObjectToScene将对象从旧场景移动到新场景。从医生那里:

MoveGameObjectToScene 将GameObject从当前场景移动到新场景。 您只能将根GameObjects从一个场景移动到另一个场景。这意味着要移动的GameObject不能是其场景中任何其他GameObject的子类。这只适用于移动到已经加载(加性)的场景中的GameObjects。如果您想要加载单个场景,请确保在DontDestroyOnLoad上使用您想要移动到新场景的GameObject,否则,在它加载新场景时,统一会删除它。

举个例子:

代码语言:javascript
复制
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);
    }
}
票数 4
EN

Stack Overflow用户

发布于 2021-03-18 21:14:49

使用PrefabUtility.InstantiatePrefab。它允许指定目标场景。

票数 0
EN

Stack Overflow用户

发布于 2018-05-02 23:46:00

有两种选择:

  1. 使用协同线等待加载新场景的
    • 我不完全确定这是否有效,因为第一个场景将被卸载,脚本可能会提前结束,除非它在DoNotDestroyOnLoad对象中的部分。

  1. 使用新场景中的脚本来生成预置文件。
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50144997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档