Skip to content

Instantly share code, notes, and snippets.

@mandarinx
Last active November 5, 2022 16:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mandarinx/8a1dcffde7efff39806b232e5be6088d to your computer and use it in GitHub Desktop.
Save mandarinx/8a1dcffde7efff39806b232e5be6088d to your computer and use it in GitHub Desktop.
Unity3D: Detect when play mode changes to what
// For Unity versions newer than 2017.1
using UnityEditor;
[InitializeOnLoad]
public class DetectPlayModeChanges {
static DetectPlayModeChanges() {
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
private static void OnPlayModeStateChanged(PlayModeStateChange state) {
switch (state) {
case PlayModeStateChange.ExitingEditMode:
// Do whatever before entering play mode
break;
case PlayModeStateChange.EnteredPlayMode:
// Do whatever after entering play mode
break;
case PlayModeStateChange.ExitingPlayMode:
// Do whatever before returning to edit mode
break;
case PlayModeStateChange.EnteredEditMode:
// Do whatever after returning to edit mode
break;
}
}
}
// For Unity versions up to 2017.1
using UnityEditor;
public static class EditorState {
public static bool willEnterPlayMode {
get { return !EditorApplication.isPlaying
&& EditorApplication.isPlayingOrWillChangePlaymode; }
}
public static bool didEnterPlayMode {
get { return EditorApplication.isPlaying
&& EditorApplication.isPlayingOrWillChangePlaymode; }
}
public static bool willExitPlayMode {
get { return EditorApplication.isPlaying
&& !EditorApplication.isPlayingOrWillChangePlaymode; }
}
public static bool didExitPlayMode {
get { return !EditorApplication.isPlaying
&& !EditorApplication.isPlayingOrWillChangePlaymode; }
}
}
[InitializeOnLoad]
public class DetectPlayModeChanges {
static DetectPlayModeChanges() {
EditorApplication.playmodeStateChanged += OnPlayModeStateChanged;
}
private static void OnPlayModeStateChanged() {
if (EditorState.willEnterPlayMode) {
// Do whatever before entering play mode
}
if (EditorState.didEnterPlayMode) {
// Do whatever after entering play mode
}
if (EditorState.willExitPlayMode) {
// Do whatever before returning to edit mode
}
if (EditorState.didExitPlayMode) {
// Do whatever after returning to edit mode
}
}
}
@zwcloud
Copy link

zwcloud commented Mar 3, 2019

Works very well on both Unity 5.6 and 2018.3. Thank you for sharing this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment