Last active
December 2, 2023 04:03
-
-
Save nothke/85f04308b07c6a133b92c3f7e98fcdcc to your computer and use it in GitHub Desktop.
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
// Rebinding using InputSystem from Prokuv'o | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.InputSystem; | |
public class Rebinder : MonoBehaviour | |
{ | |
public bool bindingInProgress { get; private set; } | |
// Latch UI onto this for binding complete callback | |
public delegate void BindingComplete(); | |
public event BindingComplete OnBindingComplete; | |
// Debug | |
public Transform inputPreview; | |
Vector2 moveInput; | |
bool interactInput; | |
#if UNITY_EDITOR | |
// For visual debugging purposes only | |
private void Update() | |
{ | |
for (int i = 0; i < 2; i++) | |
{ | |
DomacinInputManager.Actions p = i == 0 ? | |
DomacinInputManager.e.p1 : | |
DomacinInputManager.e.p2; | |
interactInput = p.interactAction.triggered; | |
float x = p.moveLeftAction.ReadValue<float>() == 1 ? -1 : p.moveRightAction.ReadValue<float>() == 1 ? 1 : 0; | |
float y = p.moveDownAction.ReadValue<float>() == 1 ? -1 : p.moveUpAction.ReadValue<float>() == 1 ? 1 : 0; | |
moveInput = new Vector2(x, y); | |
} | |
if (inputPreview) | |
inputPreview.position = new Vector3(moveInput.x, moveInput.y); | |
} | |
#endif | |
public void StartRebindDirection(int player, int dir) | |
{ | |
DomacinInputManager.Actions p = player == 0 ? | |
DomacinInputManager.e.p1 : | |
DomacinInputManager.e.p2; | |
if (!bindingInProgress) | |
{ | |
var action = | |
dir == 0 ? p.moveLeftAction : | |
dir == 1 ? p.moveRightAction : | |
dir == 2 ? p.moveUpAction : | |
dir == 3 ? p.moveDownAction : | |
p.interactAction; | |
Debug.Log("Started rebinding " + action.name); | |
// You MUST disable the action during rebinding | |
action.Disable(); | |
action.PerformInteractiveRebinding() | |
.WithControlsExcluding("Mouse") | |
.WithCancelingThrough("<Keyboard>/escape") | |
.OnMatchWaitForAnother(0.1f) | |
.OnApplyBinding((op, keyPath) => | |
{ | |
Debug.Log("End binding"); | |
// Necessary, missed out from docs: | |
action.ApplyBindingOverride(0, keyPath); | |
Debug.Log("Bindings " + op.action.bindings[0]); | |
}) | |
.OnComplete(op => | |
{ | |
op.Dispose(); | |
Debug.Log("Binding complete"); | |
action.Enable(); | |
bindingInProgress = false; | |
OnBindingComplete?.Invoke(); | |
}) | |
.OnCancel((op) => | |
{ | |
op.Dispose(); | |
Debug.Log("Canceled binding"); | |
bindingInProgress = false; | |
action.Enable(); | |
OnBindingComplete?.Invoke(); | |
}) | |
.Start(); | |
bindingInProgress = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment