Skip to content

Instantly share code, notes, and snippets.

@kamgam
Created April 19, 2023 08:48
Show Gist options
  • Save kamgam/7aa751c025ef6c35a75aecd53014b040 to your computer and use it in GitHub Desktop.
Save kamgam/7aa751c025ef6c35a75aecd53014b040 to your computer and use it in GitHub Desktop.
This adds a simple on/off checkbox to the Tools menu that allows you to toggle between starting with the current scene or the first scene in the build settings.
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
using UnityEditor.SceneManagement;
namespace Kamgam
{
/// <summary>
/// Start With First Scene<br />
/// Sometimes when working on a scene in Unity you do not necessarily want the play mode
/// to start with that scene (which is the default behavior). Instead, you may want it to
/// start as it would in a build (aka the first scene is used).<br /><br />
/// This adds a simple on/off checkbox to the Tools menu.
/// </summary>
/// <description>
/// Based on an idea on this thread:
/// http://forum.unity3d.com/threads/157502-Executing-first-scene-in-build-settings-when-pressing-play-button-in-editor
/// </description>
[InitializeOnLoad]
public static class StartWithFirstScene
{
private const string NAME = "Tools/Start with first scene";
static bool isEnabled
{
get
{
return EditorPrefs.GetBool(NAME, false);
}
set
{
EditorPrefs.SetBool(NAME, value);
SceneListChanged();
}
}
[MenuItem(NAME, false, 0)]
static void LoadFirstScene()
{
isEnabled = !isEnabled;
}
[MenuItem(NAME, true, 0)]
static bool ValidateLoadFirstScene()
{
Menu.SetChecked(NAME, isEnabled);
return true;
}
static StartWithFirstScene()
{
SceneListChanged();
EditorBuildSettings.sceneListChanged += SceneListChanged;
}
static void SceneListChanged()
{
if (!isEnabled)
{
EditorSceneManager.playModeStartScene = default;
return;
}
//Ensure at least one build scene exist.
if (EditorBuildSettings.scenes.Length == 0)
{
Debug.Log("No Scenes in Build Settings");
isEnabled = false;
return;
}
//Reference the first scene
SceneAsset theScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(EditorBuildSettings.scenes[0].path);
// Set Play Mode scene to first scene defined in build settings.
EditorSceneManager.playModeStartScene = theScene;
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment