[Unity&C#]输入任意按键返回对应的字符串

来源:互联网 发布:csol频繁网络问题 编辑:程序博客网 时间:2024/05/16 02:45

本文参考 参考资料1,探究


按钮按下,调用函 数StartAssignment

public void StartAssignment(string keyName){if(!waitingForKey)StartCoroutine(AssignKey(keyName));}

StarCoroutine 是开启一个协程,参考 参考资料2、3

进入协程函数

/*AssignKey takes a keyName as a parameter. The * keyName is checked in a switch statement. Each * case assigns the command that keyName represents * to the new key that the user presses, which is grabbed * in the OnGUI() function, above. */public IEnumerator AssignKey(string keyName){waitingForKey = true;yield return WaitForKey(); //Executes endlessly until user presses a keyswitch(keyName){case "forward":GameManager.GM.forward = newKey; //Set forward to new keycodebuttonText.text = GameManager.GM.forward.ToString(); //Set button text to new keyPlayerPrefs.SetString("forwardKey", GameManager.GM.forward.ToString()); //save new key to PlayerPrefsbreak;case "backward":GameManager.GM.backward = newKey; //set backward to new keycodebuttonText.text = GameManager.GM.backward.ToString(); //set button text to new keyPlayerPrefs.SetString("backwardKey", GameManager.GM.backward.ToString()); //save new key to PlayerPrefsbreak;case "left":GameManager.GM.left = newKey; //set left to new keycodebuttonText.text = GameManager.GM.left.ToString(); //set button text to new keyPlayerPrefs.SetString("leftKey", GameManager.GM.left.ToString()); //save new key to playerprefsbreak;case "right":GameManager.GM.right = newKey; //set right to new keycodebuttonText.text = GameManager.GM.right.ToString(); //set button text to new keyPlayerPrefs.SetString("rightKey", GameManager.GM.right.ToString()); //save new key to playerprefsbreak;case "jump":GameManager.GM.jump = newKey; //set jump to new keycodebuttonText.text = GameManager.GM.jump.ToString(); //set button text to new keyPlayerPrefs.SetString("jumpKey", GameManager.GM.jump.ToString()); //save new key to playerprefsbreak;}yield return null;}
等待 按下任意键

协程函数

//Used for controlling the flow of our below CoroutineIEnumerator WaitForKey(){while(!keyEvent.isKey)yield return null;}


参考参考资料5
PlayerPrefs.SetString

Sets the value of the preference identified by key.

System.Enum.Parse参考参考资料4


typeof(KeyCode)

参考参考资料6


逻辑图




参考资料:

1.How To Build a Custom Input Manager in Unity C#

https://www.youtube.com/watch?v=iSxifRKQKAA

代码下载地址:https://www.dropbox.com/s/ch1f1g96wn1u9q1/InputManager.zip?dl=0

2.3.

 

[Unity&C#]协程实际案例



4.System.Enum.Parse

Enum 方法

http://blog.sina.com.cn/s/blog_8216ada70100t3d4.html

5.

PlayerPrefs.SetString

https://docs.unity3d.com/ScriptReference/PlayerPrefs.SetString.html
[Unity&]PlayerPrefs.GetString的使用案例

6.C# typeof() 和 GetType()区别

http://blog.csdn.net/letianok/article/details/7257117

7.

8.

阅读全文
0 0