evershade/Assets/Scripts/Controllers/HotkeyUIController.cs

104 lines
3.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class HotkeyUIController : MonoBehaviour
{
public static HotkeyUIController Instance;
public Transform hotkeyListContainer; // Assign the Content transform of ScrollView
private readonly Dictionary<string, GameObject> hotkeyEntries = new();
public void Awake()
{
if (Instance == null)
Instance = this;
else
Destroy(gameObject);
}
// private void Start()
// {
// PopulateHotkeyList();
// }
public void ClearChildren(Transform parentTransform)
{
// var parentTransform = parentObject.transform;
// Detach all the children from the parent
for (var i = parentTransform.childCount - 1; i >= 0; i--)
{
var childTransform = parentTransform.GetChild(i);
childTransform.SetParent(null);
}
// Destroy all the detached children
foreach (Transform child in parentTransform) Destroy(child.gameObject);
}
public void PopulateHotkeyList()
{
Debug.Log("Getting all hot keys");
var hotkeys = HotkeyManager.Instance.GetAllHotkeys();
Debug.Log("Clearing Children");
ClearChildren(hotkeyListContainer);
var hotkeyEntryPrefab = PrefabManager.Instance.GetHotkeyEntryPrefab();
foreach (var hotkey in hotkeys)
{
var entry = Instantiate(hotkeyEntryPrefab, hotkeyListContainer);
var actionName = entry.transform.Find("ActionName").GetComponent<TMP_Text>();
var keyName = entry.transform.Find("KeyName").GetComponent<TMP_InputField>();
var changeButton = entry.transform.Find("ChangeButton").GetComponent<Button>();
Debug.Log(actionName);
Debug.Log(hotkey);
Debug.Log(hotkey.Key);
Debug.Log(hotkey.Value);
Debug.Log(hotkey.Value.ToString());
actionName.text = hotkey.Key;
Debug.Log(keyName);
Debug.Log(keyName.text);
keyName.text = hotkey.Value.ToString();
var currentAction = hotkey.Key;
changeButton.onClick.AddListener(() => StartHotkeyChange(currentAction, keyName));
hotkeyEntries[currentAction] = entry;
}
}
private void StartHotkeyChange(string actionName, TMP_InputField keyNameText)
{
Debug.Log("Waiting for key change");
StartCoroutine(WaitForKey(actionName, keyNameText));
}
private IEnumerator WaitForKey(string actionName, TMP_InputField keyNameText)
{
var keyAssigned = false;
while (!keyAssigned)
{
foreach (KeyCode key in Enum.GetValues(typeof(KeyCode)))
if (Input.GetKeyDown(key))
{
HotkeyManager.Instance.UpdateHotkey(actionName, key);
keyNameText.text = key.ToString();
keyAssigned = true;
break;
}
yield return null;
}
}
}