Is there any way to convert a String to KeyCode? For example, to be so.

string stof = "J"; KeyCode kk = KeyCode.stof; Debug.Log(kk.ToString()); Π’Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ J 
  • And if to translate string value in char? - tCode

1 answer 1

Since KeyCode is enum , enum.Parse should help enum.Parse . But you need to "guess" the name.

It turns out that:

 (KeyCode)Enum.Parse(typeof(KeyCode), stof) 

It supports only letters.

A more rigorous version of this (at the same time supports the numbers):

 char c = 'J'; // Π½Π°Ρ‡ΠΈΠ½Π°Π΅ΠΌ с символа, Ρ‚. ΠΊ. Π² строкС ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ‹Ρ‚ΡŒ ΠΈΡ… ΠΌΠ½ΠΎΠ³ΠΎ string keyName; if (c >= 'A' && c <= 'Z') keyName = c.ToString(); else if (c >= '0' && c <= '9') keyName = "Alpha" + c; else throw new ArgumentException("Don't know name for this key"); KeyCode kk = (KeyCode)Enum.Parse(typeof(KeyCode), keyName); 

(I can't check, I don't have Unity.)