【问题标题】:Instantiate prefab in (another) scene在(另一个)场景中实例化预制件
【发布时间】:2021-03-19 05:14:49
【问题描述】:

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

【问题讨论】:

  • 加载新场景时是否正在卸载当前场景?

标签: c# unity3d


【解决方案1】:

实例化预制件并使用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);
    }
}

【讨论】:

  • GameObject被成功移动了非常感谢但是gameObject.activeInHierarchy为什么是假的??
  • 你的解释ِ是个天才,你代码中的评论很有创意。谢谢sssss。
【解决方案2】:

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

【讨论】:

  • 这是 UnityEditor API 的一部分,在构建中不起作用。
【解决方案3】:

两种选择:

  1. 使用协程等待新场景加载
    • 我不完全确定这是否可行,因为第一个场景会被卸载并且脚本可能会提前终止,除非它是 DoNotDestroyOnLoad 对象的一部分
  2. 使用新场景中的脚本来生成预制件

【讨论】:

  • 等待新场景加载不行我试过了
  • 没有办法在另一个场景中实例化预制件?
  • @IssamOtoz 不,另一个场景还不存在。
猜你喜欢
  • 2020-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多