简体   繁体   中英

C# 'KeyCode' does not contain a definition for 'numberKey'

I'm trying to make a shortcut from making several different "if statements". Instead I only change one value that is given by a for loop. "KeyCode.Alpha1" suggests that I press the "1" key on the top of the keyboard and so on. So the "numberKey" variable has a string stored "Alpha1" but it's reading it as just "numberKey". Then i get a error message saying 'KeyCode' does not contain a definition for 'numberKey'. Help

    private void Inventory()
    {
        for (int i = 1; i <= items.Count; i++)
        {
            string numberKey = "Alpha" + i.ToString();
            if (Input.GetKeyDown(KeyCode.numberKey))
            {
                items[currentItem].gameObject.SetActive(false);
                currentItem = i--;
                items[currentItem].gameObject.SetActive(true);
            }
        }
    }

KeyCode is an enum so you can't just dynamically build a string with the same name as an enum and expect it to work. Instead use Enum.Parse:

Input.GetKeyDown(Enum.Parse(typeof(KeyCode), numberKey, true));

Enum.Parse takes the text representation of an Enum and makes the enum from it. So it's basically saying "Return the KeyCode enum entry where the name is equal to numberKey" The boolean at the end tells it not to be case sensitive.

You might try casting between enum and int:

        int Alpha0Key = (int)KeyCode.Alpha0;

        for (int i = 0; i < items.Count; i++)
        {
            if (Input.GetKeyDown((KeyCode)(Alpha0Key+i))
            {
                items[currentItem].gameObject.SetActive(false);
                currentItem = i;
                items[currentItem].gameObject.SetActive(true);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM