Skip to content

Instantly share code, notes, and snippets.

@forestrf
Created July 29, 2021 22:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forestrf/cb75ea470f276ae3a35d9561947453cc to your computer and use it in GitHub Desktop.
Save forestrf/cb75ea470f276ae3a35d9561947453cc to your computer and use it in GitHub Desktop.
Unity Input modifier that accepts a modifier + a button but the modifier must be pressed before button
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Scripting;
using UnityEngine;
using UnityEngine.InputSystem;
namespace AshInput {
[Preserve]
[DisplayStringFormat("1º{modifier}+2º{button}")]
public class ButtonWithOneModifierOrdered : InputBindingComposite<float> {
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] // BeforeSceneLoad is needed or it will fail in builds initializing too late.
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
#endif
static void Init() {
InputSystem.RegisterBindingComposite<ButtonWithOneModifierOrdered>();
}
[InputControl(layout = "Button")] public int modifier;
[InputControl(layout = "Button")] public int button;
enum LockedState : byte { Waiting, LockedPressed, LockedUnpressed };
LockedState lockedState = LockedState.Waiting;
public override float ReadValue(ref InputBindingCompositeContext context) {
bool newModifierState = context.ReadValueAsButton(modifier);
bool newButtonState = context.ReadValueAsButton(button);
if (lockedState == LockedState.Waiting) {
if (newButtonState) lockedState = newModifierState ? LockedState.LockedPressed : LockedState.LockedUnpressed;
}
else {
if (!newButtonState) lockedState = LockedState.Waiting;
}
return lockedState == LockedState.LockedPressed ? 1 : 0;
}
public override float EvaluateMagnitude(ref InputBindingCompositeContext context) {
return ReadValue(ref context);
}
}
}
@forestrf
Copy link
Author

Just drop the file somewhere in the project and it will appear in the Controls Manager

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