Created
September 12, 2019 21:54
-
-
Save RodGreen/8d5f5452c459755d9bf6bad1015ef194 to your computer and use it in GitHub Desktop.
Automatically switches editor shortcut profile when playing Unity3D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEditor; | |
using UnityEditor.ShortcutManagement; | |
using System.Linq; | |
[InitializeOnLoad] | |
public class SwitchShortcutsProfileOnPlay | |
{ | |
private const string PlayingProfileId = "Playing"; | |
private static string _activeProfileId; | |
private static bool _switched; | |
static SwitchShortcutsProfileOnPlay() | |
{ | |
EditorApplication.playModeStateChanged += DetectPlayModeState; | |
} | |
private static void SetActiveProfile(string profileId) | |
{ | |
Debug.Log($"Activating Shortcut profile \"{profileId}\""); | |
ShortcutManager.instance.activeProfileId = profileId; | |
} | |
private static void DetectPlayModeState(PlayModeStateChange state) | |
{ | |
switch (state) | |
{ | |
case PlayModeStateChange.EnteredPlayMode: | |
OnEnteredPlayMode(); | |
break; | |
case PlayModeStateChange.ExitingPlayMode: | |
OnExitingPlayMode(); | |
break; | |
} | |
} | |
private static void OnExitingPlayMode() | |
{ | |
if (!_switched) | |
return; | |
_switched = false; | |
SetActiveProfile(_activeProfileId); | |
} | |
private static void OnEnteredPlayMode() | |
{ | |
_activeProfileId = ShortcutManager.instance.activeProfileId; | |
if (_activeProfileId.Equals(PlayingProfileId)) | |
return; // Same as active | |
var allProfiles = ShortcutManager.instance.GetAvailableProfileIds().ToList(); | |
if (!allProfiles.Contains(PlayingProfileId)) | |
return; // Couldn't find PlayingProfileId | |
_switched = true; | |
SetActiveProfile(PlayingProfileId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found it sometimes didn't always switch the profile back to the main active profile when exiting play mode. It seems the static variable _activeProfileId was getting reset when the script was reloaded when switching modes (domain reloads and possible race conditions). This seems to work more reliably (Unity 2021.3):