- Home /
LoadSceneAsync additive and moving scene root problem
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.
Answer by ScaniX · Jul 29, 2016 at 11:03 PM
Probably your wait loop is the problem. Try using yield return null
instead of the yield return WaitForEndOfFrame()
.
I also have an additional waiting loop after waiting for the operation, which I added sometime during development, but I am unsure if that is still necessary.
while (!scene.isLoaded)
yield return null;
I am doing a repositioning as well when loading the new scene (although not additive and I reposition the player, and not the scene) and I don't have a bad frame inbetween.
Maybe also check this: http://answers.unity3d.com/questions/755196/yield-return-null-vs-yield-return-waitforendoffram.html
Indeed, the problem was that WaitForEndOfFrame waited until the end of the frame, but the Async operation could finish loading anywhere in between and show visually for the remaining fraction of the frame. Yield return null returns immediately and works correctly now. Thank you!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Loading Bar in Different Scenes 1 Answer