Newer
Older
HardPoint-Project-Abertay-University-Unity3D / Assets / Scenes / Developers / Nuno / NunoToys / KeyBindingUIHandler.cs
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class KeyBindingUIHandler : MonoBehaviour
{
    [System.Serializable]
    public class ActionBinding
    {
        public string name;
        public KeyCode key;
    }

    public List<TMP_InputField> inputFields;
    public List<ActionBinding> actionBindings;

    private Dictionary<string, KeyCode> keyBindings = new Dictionary<string, KeyCode>();

    private void Awake()
    {
        foreach (ActionBinding binding in actionBindings)
        {
            keyBindings[binding.name] = binding.key;
        }
        UpdateInputFields();
    }

    public void UpdateKeyBinding(int index)
    {
        TMP_InputField inputField = inputFields[index];
        string actionName = actionBindings[index].name;

        if (inputField.text.Length > 0)
        {
            KeyCode newKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), inputField.text);
            if (!keyBindings.ContainsValue(newKey))
            {
                keyBindings[actionName] = newKey;
            }
            else
            {
                Debug.Log("Key already in use");
                UpdateInputFields();
            }
        }
        else
        {
            Debug.Log("Invalid key");
            UpdateInputFields();
        }
    }

    private void UpdateInputFields()
    {
        foreach (TMP_InputField inputField in inputFields)
        {
            int index = inputFields.IndexOf(inputField);
            inputField.text = keyBindings[actionBindings[index].name].ToString();
        }
    }
}