How to switch Unity Layouts during Play and Edit Mode

I have been using the code below to switch between two layouts. “Preset Layout” for Play Mode and “Default Layout” for Edit Mode:

using UnityEngine;
using UnityEditor;

namespace Assets.Editor {
    public class AutoLayoutChanger {
        static AutoLayoutChanger() {
            EditorApplication.playmodeStateChanged = HandleOnPlayModeChanged;

        static void HandleOnPlayModeChanged() {
            // This method is run whenever the playmode state is changed.
            if (EditorApplication.isPlaying) {
                EditorUtility.LoadWindowLayout("Preset Layout");
                // do stuff when the editor is played.
            } else if (!EditorApplication.isPaused) {
                EditorUtility.LoadWindowLayout("Default Layout");
                // other than playmode

However I will always run into this error:

Failed to load window layout: System.ArgumentException: Window layout at 'Preset Layout' could not be loaded.
  at UnityEditor.WindowLayout.LoadWindowLayout (System.String path, Boolean newProjectLayoutWasCreated) [0x0008d] in C:\buildslave\unity\build\Editor\Mono\GUI\WindowLayout.cs:487 
Assets.Editor.AutoLayoutChanger:HandleOnPlayModeChanged() (at Assets/Scripts/AutoLayoutChanger.cs:14)

Does anybody know how to fix this or maybe even have code that works.

Hi. I know I am about 2 years late with an answer, but still. You need to understand that each layout is saved as a file by Unity inside system files. This describes the main problem with your code:

EditorUtility.LoadWindowLayout("full path to layout file, including file extension")

You can get your path like so:

static string layoutsPreferencesPath = Path.Combine(InternalEditorUtility.unityPreferencesFolder, "Layouts");

To use the above code you would need the following namespace:

using UnityEditorInternal;

Now, at the moment I work on Mac, so I also need to add “/default” to the path.
Finally, the file extension for the layout files is “.wlt”. So you can get all filenames with their paths like so:

string[] fileNames = Directory.GetFiles(layoutsPreferencesPath + "/default", "*.wlt");