gun*_*naf 5 c# unity-game-engine
我们尝试了不同的方法将 UI 对象移动到另一个场景,但我们失败了。对象在画布中。
方法 1:我们使用了 LoadLevelAdditive,但是从第一个场景中移动了所有对象,而没有通过 Canvas 及其元素。
方法 2:我们使用 DontDestroyOnLoad。我们需要更改 Canvas 上的元素。DDOL 保存了场景中的最后一个位置,但我们根本无法更改对象。
你能得到一些建议吗?
谢谢。
不要使用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!");
}
Run Code Online (Sandbox Code Playgroud)