Last active
November 5, 2022 16:49
-
-
Save mandarinx/8a1dcffde7efff39806b232e5be6088d to your computer and use it in GitHub Desktop.
Unity3D: Detect when play mode changes to what
This file contains 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
// 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; | |
} | |
} | |
} |
This file contains 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
// 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works very well on both Unity 5.6 and 2018.3. Thank you for sharing this!