直接先来代码
脚本1:keyCodeSet
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class KeyCodeSet : MonoBehaviour
{
public GUIStyle style;
public string tip;
private bool SumActive;
private bool once = false;
private Button ChangingKey;
public void ActiveKeySave(Button this_button)
{
ChangingKey = this_button;
SumActive = true;
once = true;
}
private void OnGUI()
{
if (SumActive)
{
GUI.Label(new Rect(Screen.width / 2 - 200, Screen.height / 2, 200, 200), tip, style);
if (once)
{
StartCoroutine(KeyGet());
once = false;
}
}
}
IEnumerator KeyGet()
{
while (true) //等待按键
{
if (Input.anyKeyDown)
{
foreach (KeyCode keycode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKeyDown(keycode))
{
ChangingKey.GetComponentInChildren<Text>().text = keycode.ToString(); //改UI显示
InputManager.GetInstance().inputSystemDic[ChangingKey.transform.name] = keycode; //通过名字改按键字典
InputManager.GetInstance().Show();
}
SumActive = false;
}
break;
}
yield return null;
}
}
}
脚本2:InputManager
using System.Collections.Generic;
using UnityEngine;
public class InputManager : SingletonAutoMono<InputManager> //继承该类使inputmanager变为单例,这个类就不放出来了,自己直接在inputmanager内写是一样的。
{
public Dictionary<string, KeyCode> inputSystemDic = new Dictionary<string, KeyCode>() {
{ "teleporterKey", KeyCode.Space},
{ "attackKey", KeyCode.Mouse0},
{ "leftChangeWeapon", KeyCode.Q},
{ "rightChangeWeapon", KeyCode.E},
{ "callReplisome", KeyCode.F},
{ "dodge", KeyCode.Mouse1 },
};
public void Show() //打印字典内容
{
foreach (var item in inputSystemDic)
{
Debug.Log(item);
}
}
public void ResetIps() //重置字典内容
{
inputSystemDic = new Dictionary<string, KeyCode>() {
{ "teleporterKey", KeyCode.Space},
{ "attackKey", KeyCode.Mouse0},
{ "leftChangeWeapon", KeyCode.Q},
{ "rightChangeWeapon", KeyCode.E},
{ "callReplisome", KeyCode.F},
{ "dodge", KeyCode.Mouse1 },
};
}
}
简单解释:
InputManager:字典设置键位对应的默认键值,并设置为单例,其他类在调用时通过inputmanager去获取对应键值,例:Input.GetKeyDown(InputManager.GetInstance().inputSystemDic[“dodge”],去检测字典中key为dodge的键所对应的value(keycode类型)。这样,我们后续只需更改字典的value就可实现改建功能。
Inputmanager也需要dontdestory,保证全局一直存在。
KeyCodeSet:挂载到任意物体上,把内部ActiveKeySave方法挂载到一个button上(一般游戏改键的时候都是在改键界面先按对应键位的一个按钮再输入想改成的键位才能成功改吧,这里实现的也是类似功能)。在改键界面点击对应按键button后执行协程,进行相应改键实现。
总的来说就是,拿字典去存对应功能的按键,调用的时候通过字典key获取value;改的时候通过字典key改对应value。而InputManager的DontDesotory和单例,去保证改键后跳转新场景字典内容也是更改之后的。
如果想实现持久化存储改键,只需要在退出游戏的时候保存一下当前键位设置,进入游戏的时候第一步就是将存储的键位设置放到InputManager里面即可。用PlayerPrefs即可实现(提示:keycode为枚举类型,可以转换为int类型去存储;同样,也可以通过int类型转为keycode类型)。
上述为个人理解,欢迎指正