将GameObject移动/转移到另一个场景

时间:2017-08-21 13:42:18

标签: c# unity3d

我们尝试了将UI对象移动到另一个场景的不同方法,但我们失败了。 Over对象在Canvas中。

方法1:我们使用了LoadLevelAdditive,但是移动了第一个场景中的所有对象而没有使用Canvas的所有对象。

方法2:我们使用了DontDestroyOnLoad。我们需要在Canvas上更改我们的元素。 DDOL保存场景中的最后位置,但我们根本无法更改对象。

你能得到一些建议吗?

感谢。

1 个答案:

答案 0 :(得分:3)

不要使用Application.LoadLevelXXX。这些是已弃用的功能。如果您使用的是旧版Unity,请以其他方式更新,否则您可能无法使用以下解决方案。

首先,使用SceneManager.LoadSceneAsync加载场景。将allowSceneActivation设置为false,以便加载后场景不会自动激活。

问题的主要解决方案是SceneManager.MoveGameObjectToScene函数,用于将GameObject从一个场景转移到另一个场景。加载场景后调用,然后调用SceneManager.SetActiveScene激活场景。以下是一个例子。

public GameObject UIRootObject;
private AsyncOperation sceneAsync;

void Start()
{
    StartCoroutine(loadScene(2));
}

IEnumerator loadScene(int index)
{
    AsyncOperation scene = SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
    scene.allowSceneActivation = false;
    sceneAsync = scene;

    //Wait until we are done loading the scene
    while (scene.progress < 0.9f)
    {
        Debug.Log("Loading scene " + " [][] Progress: " + scene.progress);
        yield return null;
    }
    OnFinishedLoadingAllScene();
}

void enableScene(int index)
{
    //Activate the Scene
    sceneAsync.allowSceneActivation = true;


    Scene sceneToLoad = SceneManager.GetSceneByBuildIndex(index);
    if (sceneToLoad.IsValid())
    {
        Debug.Log("Scene is Valid");
        SceneManager.MoveGameObjectToScene(UIRootObject, sceneToLoad);
        SceneManager.SetActiveScene(sceneToLoad);
    }
}

void OnFinishedLoadingAllScene()
{
    Debug.Log("Done Loading Scene");
    enableScene(2);
    Debug.Log("Scene Activated!");
}
相关问题