Last active
April 29, 2025 21:48
-
-
Save maoyeedy/0b372fc60cbe6a9f138841946652d30c to your computer and use it in GitHub Desktop.
[Unity] Toggle Play Mode with Gamepad Buttons
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
#if UNITY_EDITOR && ENABLE_INPUT_SYSTEM | |
using UnityEditor; | |
using UnityEngine; | |
using UnityEngine.InputSystem; | |
namespace Project.Editor | |
{ | |
/// <summary> | |
/// Toggles play mode when pressing both Start and Select. | |
/// You may alter the trigger at the <see cref="IsGamepadPressed" />> method. | |
/// </summary> | |
[InitializeOnLoad] | |
public static class PlayModeGamepadToggle | |
{ | |
/// <summary> | |
/// GameObject that holds the <see cref="ToggleComponent" />. | |
/// </summary> | |
private static GameObject _toggleObject; | |
static PlayModeGamepadToggle() | |
{ | |
EditorApplication.update += Update; | |
EditorApplication.playModeStateChanged += OnPlayModeStateChanged; | |
} | |
private static void Update() | |
{ | |
if (EditorApplication.isPlaying) return; | |
if (IsGamepadPressed()) EditorApplication.EnterPlaymode(); | |
} | |
private static void OnPlayModeStateChanged(PlayModeStateChange state) | |
{ | |
switch (state) | |
{ | |
case PlayModeStateChange.EnteredPlayMode: | |
_toggleObject = new GameObject("ToggleComponent") { hideFlags = HideFlags.HideAndDontSave }; | |
_toggleObject.AddComponent<ToggleComponent>(); | |
return; | |
case PlayModeStateChange.ExitingPlayMode when _toggleObject != null: | |
Object.DestroyImmediate(_toggleObject); | |
break; | |
} | |
} | |
private static bool IsGamepadPressed() | |
{ | |
var gamepad = Gamepad.current; | |
if (gamepad == null) return false; | |
return gamepad.startButton.isPressed && gamepad.selectButton.isPressed; | |
} | |
private class ToggleComponent : MonoBehaviour | |
{ | |
private void Update() | |
{ | |
if (!EditorApplication.isPlaying) return; | |
if (IsGamepadPressed()) EditorApplication.ExitPlaymode(); | |
} | |
} | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Most of the time, I had to put gamepad aside so that I can press Ctrl+P or click the Play button.
Then I’d have to pick the gamepad up again to continue playtesting.
That is clearly user-unfriendly.