Different Action Keys check that I've used somewhere before

I have done a different ‘keys check’ before that may or may not be useful here.

private void CheckSpecialAbilityKeys()
{
    var actionStore = GetComponent<ActionStore>();
    var keyOffset = (int)KeyCode.Alpha1;
    var slotCount = 6; // this will probably be configured
    for (var i = 0; i < slotCount; i++)
    {
        if (Input.GetKeyDown((KeyCode)(i + keyOffset)))
            actionStore.Use(i, gameObject);
    }
}

It’s not super obvious but enums can be cast to integers (and back), and we are fortunate enough that the number keys in the KeyCode enum are sequential. So, what I am doing here is to get the key where we want to start (KeyCode.Alpha1) and casting it to an integer. This is our offset. Then I just have a for loop that loops through values 0 to however many slots we have and adds the i to the offset.
So first loop we’ll have 0 + keyOffset which remains the same so we get the value of KeyCode.Alpha1 and we check if it was pressed. If it was pressed, we also have the index in i so we can just Use that slot. Next loop, we’ll have 1 + keyOffset which matches KeyCode.Alpha2. etc.

4 Likes

Well done!
That is much more efficient than the way Sam shows here.

Interestingly enough, when you get to the Shops and Abilities course, you’ll see that Sam has seen the error of his ways and introduced a method with the same conversion.

1 Like

Thank you a lot for sharing this great knowledge. This is way better.

Privacy & Terms