using UnityEngine; using System.Collections.Generic; public class KeyBindingManager : MonoBehaviour { private static Dictionary keyBindings = new Dictionary(); private void Awake() { //Debug.Log("KeyBindingManager Awake() 被调用,开始加载按键映射..."); if (keyBindings.Count == 0) { LoadKeyBindings(); } } /// 获取颜色对应的按键 public static KeyCode GetKeyForColor(string color) { if (keyBindings.TryGetValue(color.ToLower(), out KeyCode key)) { return key; } //Debug.LogError($"未找到颜色 {color} 对应的按键!请检查 KeyBindingManager 是否正确初始化。"); return KeyCode.None; } /// 修改按键绑定 public static void ChangeKeyBinding(string color, KeyCode newKey) { if (keyBindings.ContainsKey(color.ToLower())) { keyBindings[color.ToLower()] = newKey; } else { keyBindings.Add(color.ToLower(), newKey); } SaveKeyBindings(); } /// 存储按键绑定到 `PlayerPrefs` private static void SaveKeyBindings() { foreach (var kvp in keyBindings) { PlayerPrefs.SetInt($"KeyBinding_{kvp.Key}", (int)kvp.Value); } PlayerPrefs.Save(); } /// 从 `PlayerPrefs` 加载按键绑定 private static void LoadKeyBindings() { string[] colors = { "red", "green", "yellow", "purple", "blue" }; KeyCode[] defaultKeys = { KeyCode.D, KeyCode.F, KeyCode.Space, KeyCode.J, KeyCode.K }; for (int i = 0; i < colors.Length; i++) { if (PlayerPrefs.HasKey($"KeyBinding_{colors[i]}")) { keyBindings[colors[i]] = (KeyCode)PlayerPrefs.GetInt($"KeyBinding_{colors[i]}"); } else { keyBindings[colors[i]] = defaultKeys[i]; } } //Debug.Log("KeyBindings 初始化成功:" + string.Join(", ", keyBindings)); } }