using UnityEngine; using System.Collections.Generic; public class KeyBindingManager : MonoBehaviour { private static Dictionary keyBindings = new Dictionary(); private static readonly string[] colors = { "red", "green", "yellow", "purple", "blue" }; private static readonly KeyCode[] defaultKeys = { KeyCode.D, KeyCode.F, KeyCode.Space, KeyCode.J, KeyCode.K }; private static bool initialized = false; private void Awake() { if (!initialized) { LoadKeyBindings(); } Debug.Log("KeyBindingManager Awake() 被调用,开始加载按键映射..."); } public static KeyCode GetKeyForColor(string color) { if (!initialized) { LoadKeyBindings(); } if (string.IsNullOrEmpty(color)) return KeyCode.None; var keyLower = color.ToLower(); if (keyBindings.TryGetValue(keyLower, out KeyCode key)) { return key; } // fallback: try to map by index order for (int i = 0; i < colors.Length; i++) { if (colors[i] == keyLower) { return defaultKeys[i]; } } return KeyCode.None; } public static void ChangeKeyBinding(string color, KeyCode newKey) { if (string.IsNullOrEmpty(color)) return; var keyLower = color.ToLower(); keyBindings[keyLower] = newKey; SaveKeyBindings(); } private static void SaveKeyBindings() { for (int i = 0; i < colors.Length; i++) { var col = colors[i]; KeyCode k = defaultKeys[i]; if (keyBindings.TryGetValue(col, out KeyCode stored)) k = stored; PlayerPrefs.SetInt($"KeyBinding_{col}", (int)k); } PlayerPrefs.Save(); } private static void LoadKeyBindings() { keyBindings.Clear(); for (int i = 0; i < colors.Length; i++) { string col = colors[i]; if (PlayerPrefs.HasKey($"KeyBinding_{col}")) { keyBindings[col] = (KeyCode)PlayerPrefs.GetInt($"KeyBinding_{col}"); } else { keyBindings[col] = defaultKeys[i]; } } initialized = true; Debug.Log("KeyBindings 初始化成功:" + string.Join(", ", keyBindings)); } // Return a human-friendly display string for a KeyCode (symbols shown as their character) public static string GetDisplayName(KeyCode key) { if (key == KeyCode.Space) return "Space"; switch (key) { case KeyCode.Quote: return "'"; // single quote case KeyCode.Semicolon: return ";"; case KeyCode.Comma: return ","; case KeyCode.Period: return "."; case KeyCode.Slash: return "/"; case KeyCode.Backslash: return "\\"; case KeyCode.LeftBracket: return "["; case KeyCode.RightBracket: return "]"; case KeyCode.Minus: return "-"; case KeyCode.Equals: return "="; case KeyCode.BackQuote: return "`"; case KeyCode.Keypad0: return "Num0"; case KeyCode.Keypad1: return "Num1"; case KeyCode.Keypad2: return "Num2"; case KeyCode.Keypad3: return "Num3"; case KeyCode.Keypad4: return "Num4"; case KeyCode.Keypad5: return "Num5"; case KeyCode.Keypad6: return "Num6"; case KeyCode.Keypad7: return "Num7"; case KeyCode.Keypad8: return "Num8"; case KeyCode.Keypad9: return "Num9"; default: // For letters and named keys, use ToString(); for better readability, split "Alpha0" -> "0" string s = key.ToString(); if (s.StartsWith("Alpha") && s.Length > 5) return s.Substring(5); return s; } } }