- Home /
Converting a string to keycode
I am in need of a way to take a string(or character) and convert it into its appropriate KeyCode enum.
Ultimately, I'm trying to read in a file containing key bindings and then use the parsed information to set my GetKey calls. The way I'm wanting to do this right now is to set variables with their related functions, like "forward" for example to move the character forward. I then want to take this variable and use it in my GetKey calls (GetKey(forward), for example).
Is there an easy way to take a character (like 'w') and set it to a KeyCode for use as a variable?
This is what I'm currently doing:
if(Input.GetKey(KeyCode.W)) {
accelerationZ = accelerationRate;
}
This is what I need it to be:
if(Input.GetKey(forward)) {
accelerationZ = accelerationRate;
}
Any suggestions would be helpful! I'm willing to redesign my approach if needed. I just need some way to read in a file and use GetKey on the bound characters.
EDIT: I think I can instead just store the enum integers instead of a character in my key bindings file, however I still need to somehow store this in a variable and also retrieve the key corresponding to the enum for display in the game.
Answer by DaveA · Aug 16, 2012 at 11:30 PM
You want this I think: http://msdn.microsoft.com/en-us/library/essfb559 Enum.Parse
I really think this should say "Want this, I think you do".
Answer by Muuskii · Aug 17, 2012 at 12:08 AM
You could save yourself some trouble by looking at Custom Inputmanager v1.4
That thing looks pretty good! $$anonymous$$uch like my old friend Unreal's input manager. Looks like a 2.x version for sale too.
I haven't gotten around to testing it quite yet, but if it's GUI isn't satisfactory I'm also looking into NGUI plugin which apparently has player pref utilities, making it a candidate to integrate with cInput.
Answer by TheNewNerd · Oct 18, 2016 at 06:14 PM
I found a very basic, but tedious way of doing this. Hopefully this helps someone :) Also if anyone knows how to make this better please let me know, It would be very helpful.
using UnityEngine; using System.Collections;
public class CustomKeys : MonoBehaviour { //Variables public KeyCode Key1 = KeyCode.D; public string KeyA;
// Update is called once per frame
void Update () {
//This checks if "KeyA" = "a". If it does then it changes "Key1" to = A aka (KeyCode.A)
if (KeyA == "a")
{
Key1 = KeyCode.A;
}
}
}
Your answer
