Home > OS >  How to handle multiple key presses in Unity C#
How to handle multiple key presses in Unity C#

Time:12-05

I am new to game development in Unity and have a question regarding the handling of multiple input handling. For an example:

void Update()
{
    if (Input.GetKeyDown(KeyCode.G))
    {
        // drop current weapon here
    }
    if (Input.GetKeyDown(KeyCode.E))
    {
        // interact here
    }
}

This is the most common way I see people showing how to handle keyboard key presses, but is it the right way of doing it? I guess my question is, When does this approach lose it's effectiveness with regard to number of inputs, since right now I will be having around 10 inputs.

CodePudding user response:

This might be glitchy. They do it correctly, but a thing where some people stuck is the difference between:

void Update()
{
    if (Input.GetKeyDown(KeyCode.G))
    {
        // drop current weapon here
    }
    if (Input.GetKeyDown(KeyCode.E))
    {
        // interact here
    }
}

and

void Update()
{
    if (Input.GetKeyDown(KeyCode.G))
    {
        // drop current weapon here
    }
    else if (Input.GetKeyDown(KeyCode.E))
    {
        // interact here
    }
}

Observe the use of else if in the second one.

As per in the first snippet, both the statements are 'if' statements which will detect the pressing of both the keys at the same time. So if you press both the keys together, it might be a bit glitchy.

The second snippet, for what you want to do in here is correct. It checks if the key 'g' was pressed firstly and it leaves the other else if statement if g is pressed. And if it doesn't see any 'g' button getting down in the frame, it goes to the second else if statement.

For anything to be done like its once at a very short moment of time, its best to use the second snippet, but for movements and rotations that are done continuously, the first snippet is used.

Hope it wasn't difficult to understand!

  • Related