unity做单机游戏,按键修改,更换场景按键依旧保存(做毕业设计过程中的一些心得,第一次发文,有错误的敬请谅解)
定义新按键
KeyCode newKey;
newKey= (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString(“forward”, “W”));
直接上代码(说明一点,有的东西定义的是public公有类型的变量,需要自己在unity里赋值,最好看一下代码,然后根据条件来使用),
//自定义按键代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangeKey : MonoBehaviour {
//这里本来是能定义按钮的,但是我的Unity出了点毛病,暂时这样了
public GameObject forward;
public GameObject back;
public GameObject left;
public GameObject right;
public GameObject attack;
public GameObject skill1;
public GameObject skill2;
public GameObject skill3;
//定义的新按键
KeyCode backkey;
KeyCode forwardkey;
KeyCode rightkey;
KeyCode leftkey;
KeyCode attackkey;
KeyCode skill1key;
KeyCode skill2key;
KeyCode skill3key;
//临时按键
KeyCode curKey;
//新的按键
KeyCode newKey;
//存储按键的事件名称
string functionName = string.Empty;
//临时按钮
GameObject currentBtn;
void Awake()
{
GetBindKeys();
}
bool isPlaying = true;
bool isWaitingForKey = false;
//切换按键的输入与显示
void OnGUI()
{
if (isWaitingForKey)
{
Event e = Event.current;
if (e.isKey)
{
newKey = e.keyCode;
currentBtn.transform.Find("Text").GetComponent<Text>().text = newKey.ToString();
PlayerPrefs.SetString(functionName, newKey.ToString());
isWaitingForKey = false;
//call when config has changed
GetBindKeys();
StartCoroutine(WaitUpdate());
}
}
}
IEnumerator WaitUpdate()
{
yield return new WaitForEndOfFrame();
isPlaying = true;
}
//按钮事件,需要给按钮手动添加事件
public void ForwardBtnClick()
{
currentBtn = forward;
isPlaying = false;
currentBtn.transform.Find("Text").GetCo