Skip to content

Instantly share code, notes, and snippets.

@maoyeedy
Last active April 29, 2025 21:48
Show Gist options
  • Save maoyeedy/0b372fc60cbe6a9f138841946652d30c to your computer and use it in GitHub Desktop.
Save maoyeedy/0b372fc60cbe6a9f138841946652d30c to your computer and use it in GitHub Desktop.
[Unity] Toggle Play Mode with Gamepad Buttons
#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
@maoyeedy
Copy link
Author

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.

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