Unity3d - Load a specific scene on play mode

Tom picture Tom · Feb 23, 2016 · Viewed 10.1k times · Source

Ok, so I'm working on a small project that has a main menu and 10 levels. From time to time I edit different levels, and want to try them out, however I get a NullPointerException as my levels rely on certain variables from the main menu for the levels to work, which means I have to alter my levels, then load my main menu and play from there.

Is there something that can be done in the Unity Editor to default load a specific scene when you hit Play, and not the scene you're on?

I could obviously resolve this to something like

public bool goToMenu; //set this to true in my levels through inspector

Start()
{
    if (goToMenu)
        //then load main menu
}

but it would be really handy if there was a way to set the default level to load when hitting play mode. I've had a look in Preferences but couldn't find anything.

Thanks!

Answer

3Dynamite picture 3Dynamite · Feb 15, 2018

I made this simple script that loads the scene at index 0 in the build settings when you push Play. I hope someone find it useful.

It detects when the play button is push and load the scene. Then, everything comes back to normal.

Oh! And it automatically executes itself after opening Unity and after compile scripts, so never mind about execute it. Simply put it on a Editor folder and it works.

#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;

[InitializeOnLoadAttribute]
public static class DefaultSceneLoader
{
    static DefaultSceneLoader(){
        EditorApplication.playModeStateChanged += LoadDefaultScene;
    }

    static void LoadDefaultScene(PlayModeStateChange state){
        if (state == PlayModeStateChange.ExitingEditMode) {
            EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo ();
        }

        if (state == PlayModeStateChange.EnteredPlayMode) {
            EditorSceneManager.LoadScene (0);
        }
    }
}
#endif