Changing InputActions Bindings at runtime

Hi guys, I need some help. I want to rebind my keyboard keys for a certain action, e.g. Fire. I can’t seem to find the syntax to rebind my key to another key and I also have no clue how to save this to the InputActionAsset. I tried this code:

_inputActions.GamePlay.Fire.ApplyBindingOverride(“<Keyboard/space”, “<Keyboard/delete”);

I was hoping this would change the binding of the Fire control from space to delete (just a random chosen key). But this doesn’t seem to work. And for saving the ActionMapAsset from within code, so the user can keep his favorite keys without the need to rebind it every time he plays the game, I didn’t find a thing about that. I even don’t know if it’s possible ? Any help would be greatly appreciated. Thanks !

PS: I tried writing a parser to search for specific actions and bindings in the generated .cs file. The actions/bindings are stored in a Dictionary. Although this works, the problem is writing it back to the file on exact the same position and I have no idea if this would work at all…

Hello

Your post send me on a wild goose chase that shouldn’t have taken so long to begin with. (Also more than a single line of code would be nice for context)

My conclusion:

  • you use the wrong syntax, so the command that you suggest won’t even work. Since I have no idea what other atrocities lie in your code and how they intertwine in the spaghetticode (no offense my code is usually a mess) and I am too dumb to read the sparse documentation I suggest to not press this matter further.

  • there is a convenient way suggested here: PerformInteractiveRebinding not working although it might not fully answer your question (it only changes the binding in runtime), but should provide a solid foundation to build the missing features on top.

  • finally you can do what I realized far too late and just download the Samples, in this case the “Rebinding UI” file and use the provided scrip. You can find them in the package manager in the same place as the install files. (Just scroll, I am inpatient, I don’t scroll, this screws me over every time) I still don’t understand the scripts, but they are written by unity staff, so they must be good?

Basically my suggestion do something like this:

    using UnityEngine;
    using UnityEngine.InputSystem;
    
    public class RebindScript : MonoBehaviour
    {
        public InputActionReference Action;
        private InputActionRebindingExtensions.RebindingOperation rebindOperation; // this should be "optimised", since doing updates every frame is inefficient
    
        void Update()
        {
            if (rebindOperation != null)
                if (rebindOperation.completed)
                {
                    Action.action.Enable();// after this you can use the new key
                    Debug.Log("finished");
                }
        }
    
        public void StartInteractiveRebind()
        {
            Action.action.Disable(); // critical before rebind!!!
            rebindOperation = Action.action.PerformInteractiveRebinding()
                .WithControlsExcluding("Mouse")
                .WithCancelingThrough("<Keyboard>/escape")
                .OnMatchWaitForAnother(0.2f)
                .Start();
        }
    
    }

and than use
PlayerPrefs.GetString() and PlayerPrefs.SerString() or your method of choice to save and read the relevant settings

This should be trivial (as all things should be!)

Cordially the noisy void

Never thought I’d get an answer to my question, so thanks ! I just used the default way of input and will try to complete my project like so. But I’ll certainly take a look at the new input system and your reaction to my post later on, when I find some time :wink:

So i figured out the code you need.

First of all the correct syntax for your binding problem:
(it uses the variables suggested in the solution above)
Action.action.ApplyBindingOverride(0, <Keyboard>/delete);

As you can see an index is required. How to get the correct one if you have more than one is a different question tho.
Also note that this will only work if you only have one binding for each action. (And you will need at least one)

Now to the save and load part:

using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;

public class RebindScript : MonoBehaviour
{
    public InputActionReference thisaction;
    private InputActionRebindingExtensions.RebindingOperation rebindOperation;

    void Start()
    {
        thisaction.action.ApplyBindingOverride(0, PlayerPrefs.GetString(thisaction.action.name, thisaction.action.bindings[0].path));// load and set prefered binding it there is none the preset button is used and saved
    }

    public void StartInteractiveRebind()
    {
        //must despose of collection or else you will have a memory leak and error with crash!
        rebindOperation?.Cancel();

        void CleanUp()
        {
            rebindOperation?.Dispose();
            rebindOperation = null;
        }

        thisaction.action.Disable(); // critical before rebind!!!
        rebindOperation = thisaction.action.PerformInteractiveRebinding(0)
            .WithCancelingThrough("<Keyboard>/escape")
            .OnMatchWaitForAnother(0.2f)
            .Start()
            .OnCancel(something =>
           {
               thisaction.action.Enable();
               Debug.Log("canceled");
               CleanUp();
           })
           .OnComplete(something =>
           {
               thisaction.action.Enable();
               Debug.Log("finished");
               save();
               CleanUp();
           });
    }

    private void save()
    {
        string device = string.Empty;
        string key = string.Empty;
        thisaction.action.GetBindingDisplayString(0, out device, out key);
        PlayerPrefs.SetString(thisaction.action.name, "<" + device + ">/" + key);
        PlayerPrefs.Save();// not necessery if you close the application properly or want to implement confirmation button
    }
}

This works for simple buttons, but won’t work with composites or even Vector 2 types. There is a solution for this (the example file dose it, I am just too dense to understand it), but for a very simple project this should suffice.

Also check the thread here from time to time. They should drop some official binding save and loading functions there sometime.

Thanks man for the time and effort you’ve put in this to figure out how it works. Much appreciated ! Trying to understand this is another thing… :wink:

Sort of doing it for myself and letting others partake in my findings. It is mostly me sifting through the example code and trying to understand it myself step by step.

To anyone following along at home my personal recommendation is to modify the example code with the saving additions, since my script is sort of spotty and unreliable. The devs sort of promised to implement a save system some time, so all this will become obsolete in a matter of moths (my guess).

Anyway… here is my composite saving code:

using UnityEngine;
using UnityEngine.InputSystem;

public class RebindScript : MonoBehaviour
{
    public InputActionReference thisaction;
    public int index;

    private InputActionRebindingExtensions.RebindingOperation rebindOperation; // dosn't need to be global it's just how I wrote the code

    private int currentIndex;

    void Start()
    {
        if (thisaction.action.bindings[index].isComposite)
        {
            currentIndex = index + 1;// the bindings following a composite contain the actual bindings you can differentiate them with .ispartofcomposite

            for (int i = 1; i <= 4; i++)
            {
                thisaction.action.ApplyBindingOverride(index + i, PlayerPrefs.GetString(thisaction.action.name + "/" + thisaction.action.bindings[index + i].name, thisaction.action.bindings[index + i].path));
            }
        }
        else
        {
[INDENT]        //same as before
 }[/INDENT]
    }

    public void StartInteractiveRebindComposite()
    {
        rebindOperation?.Cancel(); // Will null out m_RebindOperation.

        void CleanUp()
        {
            rebindOperation?.Dispose();
            rebindOperation = null;
        }

        thisaction.action.Disable(); // critical before rebind!!!
        rebindOperation = thisaction.action.PerformInteractiveRebinding(currentIndex)
            .WithCancelingThrough("<Keyboard>/escape")
            .OnMatchWaitForAnother(0.2f)
            .Start()
            .OnCancel(something =>
            {
                thisaction.action.Enable();
                currentIndex = index + 1;
                Debug.Log("canceled");
                CleanUp();
            })
           .OnComplete(something =>
           {
               thisaction.action.Enable();
               Debug.Log("one more");
               UpdateBindingText();
               CleanUp();
               if (currentIndex < 4)
               {
                   currentIndex++;
                   Debug.Log(currentIndex);
                   StartInteractiveRebindComposite();
               }
               else
               {
                   currentIndex = index + 1;
                   Debug.Log("finished");
               }
           });
    }

    private void saveComposite()
    {
        for (int i = 1; i <= 4; i++)
        {
            string device = string.Empty;
            string key = string.Empty;
            thisaction.action.GetBindingDisplayString(index + i, out device, out key);
            PlayerPrefs.SetString(thisaction.action.name + "/" + thisaction.action.bindings[i].name, "<" + device + ">/" + key);
        }
        PlayerPrefs.Save();
    }
}

Note that this code is specifically designed for a composite with 4 components.
If you have fewer components it will crash, if you have more it should work fine. A decent programmer would do a bindings.count and go thru all the bindings, but that’s not my style.

Now to the entering a Vector2 thing…

Something I learned about joysticks. Turns out the joystick class has only one official stick (left stick) and the right stick must be archived through a composite with very specific values. Only Gamepads have a right and left stick.

Long story short my generic controller is considered a joystick and rebinding with only one possible Vector2 proves rather difficult. So if anyone happens to have a xbox or ps controller they could test my theory easily.

Basically I think that saving that should be just like saving a simple button on a keyboard, but I cant test this.

Ps. I have been wondering what features make you stick to the old input system? I see the new one superior in every way. Is it just the difficulty of use?

1 Like

D

Hi! Do you know any way to not rebind the same key? Something like WithControlExcluding(sameKeythatwaspressedBefore) ?

Best option I’ve seen so far is to do it after the binding is complete - essentially, you check if any other actions are set to the same binding and reset the binding if they are. Another option could be to set a bunch of WithControlExcluding procedurally based on all other available actions. Not sure which is better, but using the first option would make it easier to do a swap of the controls if you wanted.

Dude, you are a life saver! Thank you!