Last active
March 12, 2024 15:27
-
-
Save Invertex/6481a0f4c87aa893bbdb4962baae4454 to your computer and use it in GitHub Desktop.
Unity Editor Input example using the New Input System
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 UnityEditor; | |
using UnityEngine; | |
#if ENABLE_INPUT_SYSTEM | |
using UnityEngine.InputSystem; | |
#endif | |
//Simple Editor-side New Input System capture | |
namespace Invertex.UnityEditor.InputTools | |
{ | |
[InitializeOnLoad] | |
static class EditorInputCapture | |
{ | |
#if ENABLE_INPUT_SYSTEM | |
private readonly static EditorInputButton keyP; | |
readonly static EditorInputButton gamepadStartBtn; | |
private static void EditorUpdate() | |
{ | |
keyP.Update(); | |
gamepadStartBtn.Update(); | |
} | |
static EditorInputCapture() | |
{ | |
keyP = new EditorInputButton("<Keyboard>/p"); | |
keyP.OnPressDown += () => { Debug.Log("P Pressed!"); }; | |
keyP.OnPressUp += () => { Debug.Log("P Depressed!"); }; | |
keyP.OnPressHeld += () => { Debug.Log("P Held!"); }; | |
gamepadStartBtn = new EditorInputButton("<Gamepad>/start"); | |
gamepadStartBtn.OnPressDown += () => { | |
Debug.Log("Start Pressed!"); | |
EditorApplication.isPlaying = !EditorApplication.isPlaying; | |
}; | |
gamepadStartBtn.OnPressUp += () => { Debug.Log("Start Depressed!"); }; | |
gamepadStartBtn.OnPressHeld += () => { Debug.Log("Start Held!"); }; | |
EditorApplication.update += EditorUpdate; //Could also just assign the key.Update() here if you don't need to process keys in a certain order. | |
} | |
private class EditorInputButton | |
{ | |
private readonly InputControl button; | |
public bool PressDown { get; private set; } | |
public bool PressHeld { get; private set; } | |
public bool PressUp { get; private set; } | |
public delegate void PressAction(); | |
public PressAction OnPressDown; | |
public PressAction OnPressHeld; | |
public PressAction OnPressUp; | |
public void Update() | |
{ | |
if (button != null && button.device.enabled) | |
{ | |
bool pressed = button.IsPressed(); | |
if (pressed) | |
{ | |
if (!PressHeld) | |
{ | |
PressDown = PressHeld = true; | |
OnPressDown?.Invoke(); | |
} | |
else | |
{ | |
PressDown = false; | |
OnPressHeld?.Invoke(); | |
} | |
} | |
else if (PressHeld) | |
{ | |
PressHeld = false; | |
PressUp = true; | |
OnPressUp?.Invoke(); | |
} | |
else { PressUp = false; } | |
} | |
} | |
public EditorInputButton(string controlPath) | |
{ | |
button = InputSystem.FindControl(controlPath); | |
if (button == null) { Debug.LogWarning("Couldn't find button mapping: " + controlPath + "\n Device may not be connected."); } | |
} | |
} | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment