75 lines
2.1 KiB
C#
75 lines
2.1 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
|
|
public class KeyBindingManager : MonoBehaviour
|
|
{
|
|
private static Dictionary<string, KeyCode> keyBindings = new Dictionary<string, KeyCode>();
|
|
|
|
private void Awake()
|
|
{
|
|
Debug.Log("KeyBindingManager Awake() 被调用,开始加载按键映射...");
|
|
|
|
if (keyBindings.Count == 0)
|
|
{
|
|
LoadKeyBindings();
|
|
}
|
|
}
|
|
|
|
/// <summary> 获取颜色对应的按键 </summary>
|
|
public static KeyCode GetKeyForColor(string color)
|
|
{
|
|
if (keyBindings.TryGetValue(color.ToLower(), out KeyCode key))
|
|
{
|
|
return key;
|
|
}
|
|
Debug.LogError($"未找到颜色 {color} 对应的按键!请检查 KeyBindingManager 是否正确初始化。");
|
|
return KeyCode.None;
|
|
}
|
|
|
|
/// <summary> 修改按键绑定 </summary>
|
|
public static void ChangeKeyBinding(string color, KeyCode newKey)
|
|
{
|
|
if (keyBindings.ContainsKey(color.ToLower()))
|
|
{
|
|
keyBindings[color.ToLower()] = newKey;
|
|
}
|
|
else
|
|
{
|
|
keyBindings.Add(color.ToLower(), newKey);
|
|
}
|
|
|
|
SaveKeyBindings();
|
|
}
|
|
|
|
/// <summary> 存储按键绑定到 `PlayerPrefs` </summary>
|
|
private static void SaveKeyBindings()
|
|
{
|
|
foreach (var kvp in keyBindings)
|
|
{
|
|
PlayerPrefs.SetInt($"KeyBinding_{kvp.Key}", (int)kvp.Value);
|
|
}
|
|
PlayerPrefs.Save();
|
|
}
|
|
|
|
/// <summary> 从 `PlayerPrefs` 加载按键绑定 </summary>
|
|
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));
|
|
}
|
|
}
|