Search Unity

Question Rebinding of Composite does not work - Buggy BindingIndex?

Discussion in 'Input System' started by BTStone, Apr 5, 2023.

  1. BTStone

    BTStone

    Joined:
    Mar 10, 2012
    Posts:
    1,422
    Hey forum,

    using Unity 2021.3.18f1
    using Input System 1.5.1


    I have an issue with rebinding composite actions. I have a custom script where I copied the interesting parts from the the rebinding sample provided by Unity.
    My script has these two methods:


    Code (CSharp):
    1. private void StartRebindOperation()
    2.         {
    3.             if (!ResolveActionAndBinding(out int bindingIndex))
    4.             {
    5.                 return;
    6.             }
    7.  
    8.             // If the binding is a composite, we need to rebind each part in turn.
    9.             if (actionToRebind.bindings[bindingIndex].isComposite)
    10.             {
    11.                 int firstPartIndex = bindingIndex + 1;
    12.                 if (firstPartIndex < actionToRebind.bindings.Count && actionToRebind.bindings[firstPartIndex].isPartOfComposite)
    13.                 {
    14.                     PerformBinding(actionToRebind, firstPartIndex, true);
    15.                 }
    16.             }
    17.             else
    18.             {
    19.                 PerformBinding(actionToRebind, bindingIndex);
    20.             }
    21.         }
    22.  
    23.         public bool ResolveActionAndBinding(out int bindingIndex)
    24.         {
    25.             bindingIndex = -1;
    26.  
    27.             if (actionToRebind == null)
    28.             {
    29.                 return false;
    30.             }
    31.  
    32.             if (string.IsNullOrEmpty(actionBindingId))
    33.             {
    34.                 return false;
    35.             }
    36.  
    37.             // Look up binding index.
    38.             Guid bindingId = new(actionBindingId);
    39.             bindingIndex = actionToRebind.bindings.IndexOf(x => x.id == bindingId);
    40.             if (bindingIndex == -1)
    41.             {
    42.                 Log.Error($"Cannot find binding with ID '{bindingId}' on '{actionToRebind}'", this);
    43.                 return false;
    44.             }
    45.  
    46.             return true;
    47.         }

    In my test case I want to rebind the "PrimaryMovement" Action, the bindings look like this:

    RebindingComposite_Bindings.png

    Now the rebinding doesnt work at all, so I started the debugger and monitored some values and the issue is the binding index apparently.

    When ResolveActionAndBinding() is called in StartRebindingOperation, this line here:

    Code (CSharp):
    1.             bindingIndex = actionToRebind.bindings.IndexOf(x => x.id == bindingId);
    returns an int of 11, so the bindinIndex becomes 11.
    And then StartRebindingOperation goes on with this bindingIndex and in this line here:

    Code (CSharp):
    1.             if (actionToRebind.bindings[bindingIndex].isComposite)
    returns false, since that binding with this index is not a composite, but apparently it seems to be part of a composite.

    These are all the bindings by index when looking into them via the debugger:

    RebindingComposite_Issue_01.png


    Now when I inspect the bindings of the actionToRebind and looked into the 11th index and to what it belongs it seems the binding index I would need is 10, since this binding's composite bool value is true, but for some reason I do get 11:

    RebindingComposite_Issue_02.png


    I am not sure if this is maybe a tiny bug here? Or if my setup is maybe wrong?


    And while I am here, another question would be: As you can see in the binding screenshot above I have two mappings for both the Keyboard and the Gamepad?
    How would I need to adjust the code in order to be able to rebind BOTH variations, the binding with the left stick and the binding with the dpad for example?
     
  2. Is there any reason you don't use the method (
    actionToRebind.GetBindingIndex
    ) they made for exactly this?

    See: GetBindingIndex
    Similar usage as in the mask (so you just give a mapping binding
    new InputBinding { id = "<id>" }
    )
     
  3. BTStone

    BTStone

    Joined:
    Mar 10, 2012
    Posts:
    1,422
    @Lurking-Ninja Well, you got me there.
    The reason I didnt use it is that I just copied from the sample...but with this approach I have to pass in the hardcoded id path as a string, but I'd like to avoid that or is there no other way?
    And is this approach actually a solution? What's the difference to the IndexOf call in this context?
     
  4. ? I'm not sure about what you mean by this, but
    new InputBinding { id = bindingId }
    should work.

    But, I don't know if this is a solution, and reading up on InputBinding in the documentation, I doubt it.
    What you can do is this:
    You take what you find by your search. Then check if it's a composite binding by checking its isComposite property.
    If it is, you have what you're looking for.
    If not, then check it's isPartOfComposite property. If it's false, you exit since there is no composite binding for this binding.
    If isPartOfComposite property is true, you can start to lower your index one by one and get the previous binding in the bindings array until you find the very first (closest) previous binding with the
    isComposite == true
    .

    You can do this, because
     
  5. BTStone

    BTStone

    Joined:
    Mar 10, 2012
    Posts:
    1,422
    In your previous post you wrote this:

    new InputBinding { id = "<id>" }

    And this seemed like I had to hardcode the string, that's why I said that.

    Yeah I thought about doing it like this, yes, but my question is:
    why do I get the wrong index in the first place? When I look at the sample script provided by Unity which is basically the same code and the sample scene and debug it there I get the correct bindingIndex.
    Maybe @Schubkraft can shed some light on this? I would like to know if this is maybe buggy behaviour, if so I'd report this asap :)
     
  6. Since you didn't really share what you have stored about these, I'm not sure you get the wrong index. You probably store the id of the first binding of the composite you're looking for.
     
  7. BTStone

    BTStone

    Joined:
    Mar 10, 2012
    Posts:
    1,422
    I think I cant follow you @Lurking-Ninja , what do you mean by "you didnt really share what you have stored about these"?
     
  8. I mean I have no way of validating that the
    bindingId
    you are using to find a particular binding is the composite binding's id (index 10) or the first binding inside of that composite (index 11).
    So where do you get the value of the
    bindingId
    ?
     
  9. BTStone

    BTStone

    Joined:
    Mar 10, 2012
    Posts:
    1,422
    Alright for full context, this is the whole class:

    Code (CSharp):
    1.  
    2.  
    3.     /// <summary>
    4.     /// The idea with this script is to attach it to each UI Element in the Input Game Settings where we want to allow
    5.     /// the player to rebind their input mappings
    6.     /// Each on screen input command in the options should have their own instance of this component attached
    7.     /// Use this when you want to remap gamepad actions
    8.     /// </summary>
    9.     public class RebindingInputActionGamepad : MonoBehaviour
    10.     {
    11.         [UsedImplicitly]
    12.         [ValueDropdown("@InputEditorUtils.ActionMapDropdown")]
    13.         [SerializeField]
    14.         private string inputMap;
    15.  
    16.         [ValueDropdown("@InputEditorUtils.ActionDropdown(inputMap)")]
    17.         [SerializeField]
    18.         private string inputActionName;
    19.  
    20.         [SerializeField]
    21.         private GameObject bindBlocker;
    22.  
    23.         [SerializeField]
    24.         private Button rebindButton;
    25.  
    26.         [SerializeField]
    27.         private Button resetToDefaultsButton;
    28.  
    29.         [SerializeField]
    30.         private TextMeshProUGUI bindingText;
    31.  
    32.         private readonly InputGroupType                                    gamepadGroup = InputGroupType.Gamepad;
    33.         private          InputActionRebindingExtensions.RebindingOperation rebindingOperation;
    34.         private          InputAction                                       actionToRebind;
    35.         private          string                                            actionBindingId;
    36.  
    37.  
    38.         private void OnEnable()
    39.         {
    40.             rebindButton.onClick.AddListener(OnTriggerRebinding);
    41.             resetToDefaultsButton.onClick.AddListener(OnResetToDefaults);
    42.  
    43.             actionToRebind = InputActionReference.Create(InputUtils.GetInputReferenceByAction(
    44.                                                              GameManagers.InputHandler.MOHInputActions, inputActionName));
    45.  
    46.             InputBinding binding = InputUtils.GetInputBindingForInputGroup(actionToRebind, gamepadGroup);
    47.             actionBindingId = binding.id.ToString();
    48.         }
    49.  
    50.         private void OnTriggerRebinding()
    51.         {
    52.             StartRebindOperation();
    53.         }
    54.  
    55.         private void StartRebindOperation()
    56.         {
    57.             if (!ResolveActionAndBinding(out int bindingIndex))
    58.             {
    59.                 return;
    60.             }
    61.  
    62.             // If the binding is a composite, we need to rebind each part in turn.
    63.             if (actionToRebind.bindings[bindingIndex].isComposite)
    64.             {
    65.                 int firstPartIndex = bindingIndex + 1;
    66.                 if (firstPartIndex < actionToRebind.bindings.Count && actionToRebind.bindings[firstPartIndex].isPartOfComposite)
    67.                 {
    68.                     PerformBinding(actionToRebind, firstPartIndex, true);
    69.                 }
    70.             }
    71.             else
    72.             {
    73.                 PerformBinding(actionToRebind, bindingIndex);
    74.             }
    75.         }
    76.  
    77.         public bool ResolveActionAndBinding(out int bindingIndex)
    78.         {
    79.             bindingIndex = -1;
    80.  
    81.             if (actionToRebind == null)
    82.             {
    83.                 return false;
    84.             }
    85.  
    86.             if (string.IsNullOrEmpty(actionBindingId))
    87.             {
    88.                 return false;
    89.             }
    90.  
    91.             // Look up binding index.
    92.             Guid bindingId = new(actionBindingId);
    93.             bindingIndex = actionToRebind.bindings.IndexOf(x => x.id == bindingId);
    94.             if (bindingIndex == -1)
    95.             {
    96.                 Log.Error($"Cannot find binding with ID '{bindingId}' on '{actionToRebind}'", this);
    97.                 return false;
    98.             }
    99.  
    100.             return true;
    101.         }
    102.  
    103.         private void PerformBinding(InputAction action, int bindingIndex, bool allCompositeParts = false)
    104.         {
    105.             GameManagers.InputHandler.MOHInputActions.UserInterfaceNavigation.Navigate.Disable();
    106.             if (rebindingOperation != null)
    107.             {
    108.                 rebindingOperation.Cancel();
    109.             }
    110.  
    111.             action.Disable();
    112.  
    113.             rebindingOperation = PerformBindingByGroup(action, gamepadGroup, bindingIndex, allCompositeParts);
    114.             bindBlocker.SetActive(true);
    115.             var partName = default(string);
    116.             if (bindingText != null)
    117.             {
    118.                 var text = !string.IsNullOrEmpty(rebindingOperation.expectedControlType)
    119.                     ? $"{partName}Waiting for {rebindingOperation.expectedControlType} input..."
    120.                     : $"{partName}Waiting for input...";
    121.                 bindingText.text = text;
    122.             }
    123.  
    124.             rebindingOperation.Start();
    125.         }
    126.  
    127.         private InputActionRebindingExtensions.RebindingOperation PerformBindingByGroup(InputAction action, InputGroupType groupType,
    128.                                                                                         int bindingIndex, bool allCompositeParts)
    129.         {
    130.             if (groupType == InputGroupType.Gamepad)
    131.             {
    132.                 return action.PerformInteractiveRebinding(bindingIndex)
    133.                              .OnCancel(operation => RebindCanceled(action))
    134.                              .OnComplete(operation => RebindComplete(action, bindingIndex, allCompositeParts))
    135.                              .OnMatchWaitForAnother(0.3f)
    136.                              .WithBindingGroup("<Gamepad>");
    137.             }
    138.  
    139.             Log.Error("No Gamepad groupType specified, RebindingOperation returned null");
    140.             return null;
    141.         }
    142.  
    143.         private void RebindCanceled(InputAction action)
    144.         {
    145.             GameManagers.InputHandler.MOHInputActions.UserInterfaceNavigation.Navigate.Enable();
    146.             bindBlocker.SetActive(false);
    147.  
    148.             CleanupRebinding(action);
    149.         }
    150.  
    151.         private void RebindComplete(InputAction action, int bindingIndex, bool allCompositeParts)
    152.         {
    153.             GameManagers.InputHandler.MOHInputActions.UserInterfaceNavigation.Navigate.Enable();
    154.             bindBlocker.SetActive(false);
    155.  
    156.             action.Enable();
    157.  
    158.             rebindingOperation?.Dispose();
    159.             rebindingOperation = null;
    160.  
    161.             // If there's more composite parts we should bind, initiate a rebind
    162.             // for the next part.
    163.             if (allCompositeParts)
    164.             {
    165.                 int nextBindingIndex = bindingIndex + 1;
    166.                 if (nextBindingIndex < action.bindings.Count && action.bindings[nextBindingIndex].isPartOfComposite)
    167.                 {
    168.                     PerformBinding(action, nextBindingIndex, true);
    169.                 }
    170.             }
    171.  
    172.             Message.Raise(new RebindInputActionCompleted(GameManagers.InputHandler.MOHInputActions.SaveBindingOverridesAsJson()));
    173.         }
    174.  
    175.         private void CleanupRebinding(InputAction action)
    176.         {
    177.             action.Enable();
    178.  
    179.             rebindingOperation?.Dispose();
    180.             rebindingOperation = null;
    181.         }
    182.  
    183.  
    184.         private void OnResetToDefaults()
    185.         {
    186.             if (!ResolveActionAndBinding(out int bindingIndex))
    187.             {
    188.                 return;
    189.             }
    190.  
    191.             if (actionToRebind.bindings[bindingIndex].isPartOfComposite)
    192.             {
    193.                 // It's a composite. Remove overrides from part bindings.
    194.                 for (var i = bindingIndex + 1; i < actionToRebind.bindings.Count && actionToRebind.bindings[i].isPartOfComposite; ++i)
    195.                 {
    196.                     actionToRebind.RemoveBindingOverride(i);
    197.                 }
    198.             }
    199.             else
    200.             {
    201.                 actionToRebind.RemoveBindingOverride(bindingIndex);
    202.             }
    203.         }
    204.  
    205.         private void OnDisable()
    206.         {
    207.             rebindButton.onClick.RemoveListener(OnTriggerRebinding);
    208.             resetToDefaultsButton.onClick.RemoveListener(OnResetToDefaults);
    209.         }
    210.     }
    211.  

    And these are the helper methods used in OnEnable()

    Code (CSharp):
    1.       public static InputBinding GetInputBindingForInputGroup(InputAction inputAction, InputGroupType inputGroupType)
    2.         {
    3.             int index = inputAction.bindings.IndexOf(x => string.CompareOrdinal(x.groups, inputGroupType.ToString()) == 0);
    4.  
    5.             return inputAction.bindings[index];
    6.         }
    7.  
    8.         public static InputAction GetInputReferenceByAction(MOHInputActions actions, string actionName)
    9.         {
    10.             if (actionName == nameof(actions.GeneralUI.EnterMainMenu))
    11.             {
    12.                 return actions.GeneralUI.EnterMainMenu;
    13.             }
    14.  
    15.             if (actionName == nameof(actions.PlayerMovement.PrimaryMovement))
    16.             {
    17.                 return actions.PlayerMovement.PrimaryMovement;
    18.             }
    19.  
    20.             if (actionName == nameof(actions.PlayerMovement.Run))
    21.             {
    22.                 return actions.PlayerMovement.Run;
    23.             }
    24.  
    25.             if (actionName == nameof(actions.PlayerInteraction.Interact))
    26.             {
    27.                 return actions.PlayerInteraction.Interact;
    28.             }
    29.  
    30.             if (actionName == nameof(actions.Dialogue.ProgressDialogue))
    31.             {
    32.                 return actions.Dialogue.ProgressDialogue;
    33.             }
    34.  
    35.             if (actionName == nameof(actions.Dialogue.EnterMainMenu))
    36.             {
    37.                 return actions.Dialogue.EnterMainMenu;
    38.             }
    39.  
    40.             if (actionName == nameof(actions.Cutscene.ProgressCutscene))
    41.             {
    42.                 return actions.Cutscene.ProgressCutscene;
    43.             }
    44.  
    45.             Log.Error($"ActionName: {actionName} does not match any of the InputActions!");
    46.             return null;
    47.         }
     
  10. BTStone

    BTStone

    Joined:
    Mar 10, 2012
    Posts:
    1,422
    Alright, I think I found the issue.

    So this code here was problematic after doing some debugging:

    Code (CSharp):
    1.   public static InputBinding GetInputBindingForInputGroup(InputAction inputAction, InputGroupType inputGroupType)
    2.         {
    3.             int index = inputAction.bindings.IndexOf(x => string.CompareOrdinal(x.groups, inputGroupType.ToString()) == 0);
    4.             return inputAction.bindings[index];
    5.         }
    Since my groupType is a string like this "Gamepad", it will ofc give me the binding of the first Gamepad-bound binding it finds and this is correctly at index 11.

    I adjusted the whole code now and look for the bindings in another way.

    Instead of the group type by string I search for the original binding path (or for the composite name I setup in the Action Asset if it's a composite) like this:

    Code (CSharp):
    1. public static InputBinding GetInputBindingByPath(InputAction inputAction, string path)
    2.         {
    3.             int index = inputAction.bindings.IndexOf(x => string.CompareOrdinal(x.path, path) == 0);
    4.             return inputAction.bindings[index];
    5.         }
    6.  
    7.         public static InputBinding GetInputBindingByCompositeName(InputAction inputAction, string compositeName)
    8.         {
    9.             int index = inputAction.bindings.IndexOf(x => x.isComposite && string.CompareOrdinal(x.name, compositeName) == 0);
    10.             return inputAction.bindings[index];
    11.         }
    I wrote a handy method to expose the strings of the path and compositenames and can pass them in here. Works without problems :)