Skip to content

Instantly share code, notes, and snippets.

@inslayn
Last active September 1, 2018 23:07
Show Gist options
  • Save inslayn/b1ec0587f3d72d424149eacaf58c6b42 to your computer and use it in GitHub Desktop.
Save inslayn/b1ec0587f3d72d424149eacaf58c6b42 to your computer and use it in GitHub Desktop.
Auto-boot your Unity game when entering Play mode
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
namespace EternalConstruct.Editor.Utils
{
[InitializeOnLoad]
public static class LoadInitialSceneOnEditorPlay
{
private const string InitialSceneName = @"Bootstrap";
private const string PreviousScenesPrefsKey = "_PreviousScenes";
static LoadInitialSceneOnEditorPlay()
{
EditorApplication.playModeStateChanged += change =>
{
switch (change)
{
case PlayModeStateChange.ExitingEditMode:
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
{
EditorApplication.isPlaying = false;
return;
}
var previousScenes = new List<string>();
for (var i = 0; i < SceneManager.sceneCount; i++)
{
previousScenes.Add(SceneManager.GetSceneAt(i).path);
}
EditorPrefs.SetString(PreviousScenesPrefsKey, string.Join("|", previousScenes));
previousScenes.Clear();
EditorSceneManager.OpenScene($"/Path/To/Your/Scenes/{InitialSceneName}.unity");
break;
case PlayModeStateChange.EnteredEditMode:
var scenesToRestore = EditorPrefs.GetString(PreviousScenesPrefsKey).Split('|');
for (var index = 0; index < scenesToRestore.Length; index++)
{
var scene = scenesToRestore[index];
EditorSceneManager.OpenScene(scene,
index == 0 ? OpenSceneMode.Single : OpenSceneMode.Additive);
}
EditorPrefs.DeleteKey(PreviousScenesPrefsKey);
break;
case PlayModeStateChange.ExitingPlayMode:
break;
case PlayModeStateChange.EnteredPlayMode:
break;
default:
throw new ArgumentOutOfRangeException(nameof(change), change, null);
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment