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.

You want this I think: Enum.Parse Method (System) | Microsoft Learn Enum.Parse

You could save yourself some trouble by looking at Custom Inputmanager v1.4

I found a very basic, but tedious way of doing this. Hopefully this helps someone :slight_smile: 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;
    }
}

}