Search Unity

How to bind key with string path. Bind key with listening in playmode

Discussion in 'Input System' started by JakartaIlI, May 18, 2020.

  1. JakartaIlI

    JakartaIlI

    Joined:
    Feb 6, 2015
    Posts:
    30
    Hello.
    I have string variable with path of a button. I need to bind in code, how can i do that?

    There may be a way to assign a button through listening in a gamemode like in an editor.
    A custom controller is used. During the assignment, many buttons are pressed and I need to select only one in the drop-down menu. Any ideas?
     

    Attached Files:

  2. MilitaryG

    MilitaryG

    Joined:
    Apr 26, 2021
    Posts:
    28
    I was figuring this out and found a solution:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Binding : MonoBehaviour
    6. {
    7.     int index = -1;
    8.     KeyCode[] bind = new KeyCode[10];
    9.     private void Start()
    10.     {
    11.         for (int i = 0; i < bind.Length; i++)
    12.         {
    13.             bind[i] = KeyCode.A;
    14.         }
    15.     }
    16.     private void OnGUI()
    17.     {
    18.         if(GUI.Button(new Rect(200, 200, 300, 40), ((bindName)0).ToString() + " : " + bind[0].ToString()))
    19.         {
    20.             index = 0;
    21.         }
    22.         Event e = Event.current;
    23.         if (index != -1)
    24.         {
    25.             if (e.isKey)
    26.             {
    27.                 bind[index] = e.keyCode;
    28.                 index = -1;
    29.             }
    30.         }
    31.     }
    32.     private void Update()
    33.     {
    34.         if (Input.GetKey(bind[0]))
    35.         {
    36.             Debug.Log("works");
    37.         }
    38.     }
    39. }
    40. public enum bindName
    41. {
    42.     move_forward
    43. }
    it's easy and effective all you need is to call bind one maybe you need to do few twicks for your self