Search Unity

Action "integer range" composite binding?

Discussion in 'Input System' started by MariusLangeland, Apr 28, 2020.

  1. MariusLangeland

    MariusLangeland

    Joined:
    Sep 5, 2018
    Posts:
    7
    Is it possible to create a binding similar to the 1D axis and 2D vector composites, but where each binding is mapped to a specific integer?

    My use case is an inventory system, where keyboard keys 1, 2, 3, 4, and TAB each select a different inventory group.

    Preferred mapping would then be:
    1 = 0,
    2 = 1,
    3 = 2,
    4 = 3,
    TAB = 4

    Edit: By mapping I mean number returned by ReadValue<Int>
     
  2. MariusLangeland

    MariusLangeland

    Joined:
    Sep 5, 2018
    Posts:
    7
    The answer was to create a custom composite. Albeit clunky it works

    Code (CSharp):
    1. using UnityEngine.InputSystem.Utilities;
    2. using UnityEngine.InputSystem.Layouts;
    3. using UnityEngine.InputSystem;
    4. using UnityEngine;
    5. using UnityEditor;
    6.  
    7. #if UNITY_EDITOR
    8. [InitializeOnLoad] // Automatically register in editor.
    9. #endif
    10.  
    11. [DisplayStringFormat("{firstPart}+{secondPart}")]
    12. public class IndexedComposite : InputBindingComposite<int>
    13. {
    14.     [InputControl(layout = "Button")] public int id_1;
    15.     [InputControl(layout = "Button")] public int id_2;
    16.     [InputControl(layout = "Button")] public int id_3;
    17.     [InputControl(layout = "Button")] public int id_4;
    18.     [InputControl(layout = "Button")] public int id_5;
    19.  
    20.     public override int ReadValue(ref InputBindingCompositeContext context)
    21.     {
    22.         var a = context.ReadValueAsButton(id_1);
    23.         var b = context.ReadValueAsButton(id_2);
    24.         var c = context.ReadValueAsButton(id_3);
    25.         var d = context.ReadValueAsButton(id_4);
    26.         var e = context.ReadValueAsButton(id_5);
    27.  
    28.         if (a) return 1;
    29.         if (b) return 2;
    30.         if (c) return 3;
    31.         if (d) return 4;
    32.         if (e) return 5;
    33.         return 0;
    34.     }
    35.  
    36.     static IndexedComposite()
    37.     {
    38.         InputSystem.RegisterBindingComposite<IndexedComposite>();
    39.     }
    40.  
    41.     [RuntimeInitializeOnLoadMethod]
    42.     static void Init() { } // Trigger static constructor.
    43. }