Unity C# Input System get any key and get the key name that was pressed

Viewed 1830

I am trying to make a rebinding system but the issue isn't rebinding the keys, it's getting what key was last pressed in order to determine which key to change the binding to. here's what I have so far.

public void SetBinding(GameObject key){
    if(key.GetComponent<Button>()){
        Text text = key.GetComponentInChildren<Text>();
        Button button = key.GetComponent<Button>();

        text.text = "-";
        button.interactable = false;
        Debug.Log("pressed");
         
        StartCoroutine(WaitForKey((string key)=> {
            text.text = key;
            button.interactable = true;

            Debug.Log($"Returned callback: {key}");
        }));

    }

}

IEnumerator WaitForKey(System.Action<string> callback){
    while(!Keyboard.current.anyKey.wasPressedThisFrame){
        yield return new WaitForEndOfFrame(); 
        
        // get the key that was pressed using unity's input system package.
         
    }
}
1 Answers

Okay, what I was doing wrong is the docs I have found which I thought answered the question, they were using using UnityEngine.InputSystem.Utilities; namespace which I didn't see anywhere (maybe skim read it too much) so I just had to add that and then return the callback with this

InputSystem.onAnyButtonPress
            .CallOnce(ctrl => callback(ctrl.name));
Related