0
\$\begingroup\$

How do I declare the keycodes as strings instead of selecting the keys from a list? Such that the user can input a key in inspector window and it will be read?

public string StringKey = "a";

void Update () {

   if (Input.GetKeyDown (KeyCode.StringKey)) {

   }
\$\endgroup\$
4
  • \$\begingroup\$ It seems like you want to reinvent a feature Unity already has out-of-the-box. Have you considered to just have the developer set up semantic key mappings in the Input Window? (Edit -> Project Settings -> Input) \$\endgroup\$
    – Philipp
    Commented Sep 25, 2020 at 8:53
  • \$\begingroup\$ But that is lot of work for every Unity editor application. I am just trying to implement a script that does it. \$\endgroup\$
    – Saif
    Commented Sep 25, 2020 at 8:55
  • \$\begingroup\$ Does this question from Stackoverflow help you? Convert a string to an enum in C# \$\endgroup\$
    – Philipp
    Commented Sep 25, 2020 at 9:02
  • \$\begingroup\$ Input.GetKeyDown has an override that accepts strings directly, so I'm not sure why you'd even need to convert to keycodes? The list of strings it accepts is documented here \$\endgroup\$
    – DMGregory
    Commented Sep 25, 2020 at 12:24

1 Answer 1

1
\$\begingroup\$

As Phillipp mentioned, Enum.Parse, I used the following and it worked:

if (Input.GetKeyDown((KeyCode) System.Enum.Parse(typeof(KeyCode), StringKey))) {
...
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .