I am loading multiple scenes into a main scene at run-time. Each new scene has a single root object, which I then want to position in the main scene’s world space.
My code has a small but annoying problem: I load a new scene, it then shows up at the center of the main scene. Then, after one frame, my positioning code is run and moves the new object to the correct position, resulting in a one frame glitch at every load.
IEnumerator LoadDungeonScene(string sceneName)
{
Scene activeScene = SceneManager.GetActiveScene();
AsyncOperation loadOperation = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
// Wait until the scene has loaded. Once is isDone, it actually shows up at origin,
// but I still wait another frame, which I don't want, since it shows as a visual glitch.
while (loadOperation.isDone == false)
yield return new WaitForEndOfFrame();
// Scene has loaded, get reference to root GameObject.
Scene loadedScene = SceneManager.GetSceneByName(sceneName);
Transform root = loadedScene.GetRootGameObjects()[0].transform;
// This position assignment is run 1 frame after the scene was loaded and showed up at origin.
root.position = new Vector3(100f, 200f, 300f);
// Do I need this? Why would I want to merge scenes at runtime?
SceneManager.MergeScenes(loadedScene, activeScene);
yield return null;
}
Is there any better way to load a scene, position some objects and then show them? My hacky solution might be to deactivate the root object in every scene before saving, but that would be pretty annoying as well, since there are around 20 scenes and we have several people working on them.