欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-13 21:57:44
...

本文参考 参考资料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 key

		switch(keyName)
		{
		case "forward":
			GameManager.GM.forward = newKey; //Set forward to new keycode
			buttonText.text = GameManager.GM.forward.ToString(); //Set button text to new key
			PlayerPrefs.SetString("forwardKey", GameManager.GM.forward.ToString()); //save new key to PlayerPrefs
			break;
		case "backward":
			GameManager.GM.backward = newKey; //set backward to new keycode
			buttonText.text = GameManager.GM.backward.ToString(); //set button text to new key
			PlayerPrefs.SetString("backwardKey", GameManager.GM.backward.ToString()); //save new key to PlayerPrefs
			break;
		case "left":
			GameManager.GM.left = newKey; //set left to new keycode
			buttonText.text = GameManager.GM.left.ToString(); //set button text to new key
			PlayerPrefs.SetString("leftKey", GameManager.GM.left.ToString()); //save new key to playerprefs
			break;
		case "right":
			GameManager.GM.right = newKey; //set right to new keycode
			buttonText.text = GameManager.GM.right.ToString(); //set button text to new key
			PlayerPrefs.SetString("rightKey", GameManager.GM.right.ToString()); //save new key to playerprefs
			break;
		case "jump":
			GameManager.GM.jump = newKey; //set jump to new keycode
			buttonText.text = GameManager.GM.jump.ToString(); //set button text to new key
			PlayerPrefs.SetString("jumpKey", GameManager.GM.jump.ToString()); //save new key to playerprefs
			break;
		}

		yield return null;
	}

等待 按下任意键

 

协程函数

//Used for controlling the flow of our below Coroutine
	IEnumerator 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

 

逻辑图

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

 

 

参考资料:

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

代码下载地址: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

[Unity&]PlayerPrefs.GetString的使用案例

 

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

7.

8.