Found this lecture unclear and confusing what is Sams code doing

Hi so I’ve taken Sams code directly from Git:

   public IEnumerator LoadLastScene(string saveFile)
        {
            Dictionary<string, object> state = LoadFile(saveFile);
            int buildIndex = SceneManager.GetActiveScene().buildIndex;
            if (state.ContainsKey("lastSceneBuildIndex"))
            {
                buildIndex = (int)state["lastSceneBuildIndex"];
            }
            yield return SceneManager.LoadSceneAsync(buildIndex);
            RestoreState(state);
        }

I found his explanation unclear and I don’t understand why we’re having to load the scene twice, I know Sam mentioned that the scene would load twice from a menu or something but that didn’t make sense to me.

Any scene would be loaded once going from one to other, unless I’ve miss understood something surely there’s an alternative way of resolving this race condition without having to load every scene we transition to twice?

It has made debugging messy and I imagine it is bad for performance.

Actually, the only circumstance in which you’d be loading the same scene twice is if you start the game (in the Editor) in the same scene as the value of lastSceneBuildIndex. Otherwise, you’re loading different scenes, the scene we start in, and the scene from the buildIndex. This construction allows us to Edit any scene and still have the correct scene load when we press play if a save file is present.

By the end of the last course (Shops and Abilities), we’ll always load the Main Menu scene first, and then only call LoadLastScene when we press Continue in the menu.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms