我们尝试了不同的方法将 UI 对象移动到另一个场景,但失败了。上方对象位于画布中。
方法 1:我们使用了 LoadLevelAdditive,但是从第一个场景中移动了所有对象,而没有将其元素移到 Canvas 上。
方法2:我们使用DontDestroyOnLoad。我们需要更改画布上的元素。 DDOL 保存场景中的最后位置,但我们根本无法更改对象。
不要使用
Application.LoadLevelXXX
。这些是已弃用的函数。如果您使用的是旧版本的Unity,请更新它,否则您可能无法使用下面的解决方案。
首先,使用
SceneManager.LoadSceneAsync
加载场景。将 allowSceneActivation
设置为 false
,这样场景加载后就不会自动激活。
SceneManager.MoveGameObjectToScene
函数,该函数用于将游戏对象从一个场景传输到另一个场景。加载场景后调用该函数,然后调用 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!");
}