using System; using System.Collections.Generic; using UnityEngine; public class HotkeyManager : MonoBehaviour { // Singleton instance public static HotkeyManager Instance; private readonly Dictionary actionKeys = new(); // Dictionary to store key mappings and their actions private readonly Dictionary hotkeyActions = new(); private void Awake() { // Implement singleton pattern if (Instance == null) Instance = this; else Destroy(gameObject); } private void Update() { // Check for key presses and invoke corresponding actions foreach (var hotkey in hotkeyActions) if (Input.GetKeyDown(hotkey.Key)) hotkey.Value?.Invoke(); } // Method to register a new hotkey public void RegisterHotkey(string actionName, KeyCode key, Action action) { Debug.Log("Registering Hot Key: " + actionName); if (actionKeys.ContainsKey(actionName)) UnregisterHotkey(actionKeys[actionName], action); actionKeys[actionName] = key; if (hotkeyActions.ContainsKey(key)) hotkeyActions[key] += action; else hotkeyActions[key] = action; } // Method to unregister a hotkey public void UnregisterHotkey(KeyCode key, Action action) { if (hotkeyActions.ContainsKey(key)) { hotkeyActions[key] -= action; if (hotkeyActions[key] == null) hotkeyActions.Remove(key); } } public KeyCode GetHotkey(string actionName) { return actionKeys.ContainsKey(actionName) ? actionKeys[actionName] : KeyCode.None; } public Dictionary GetAllHotkeys() { return new Dictionary(actionKeys); } public void UpdateHotkey(string actionName, KeyCode newKey) { if (actionKeys.ContainsKey(actionName)) { var oldKey = actionKeys[actionName]; if (hotkeyActions.ContainsKey(oldKey)) { var action = hotkeyActions[oldKey]; hotkeyActions.Remove(oldKey); RegisterHotkey(actionName, newKey, action); } } } // Method to clear all hotkeys public void ClearHotkeys() { hotkeyActions.Clear(); } }