Switch statement concerning inputs.

I’ve been raking my brain to convert this into a switch statement, but I can never figure it out. Can anyone help?

What this script does is it detects if the “Jump” key is pressed, and if it is, then it checks to see if A, B, C, or D is pressed. (I already renamed my axes and set them to “Jump” “A” “B” “C” and “D”)

if (Input.GetButton("Jump"))
{
if (Input.GetButton("A"))
{
print("A");
}
else if (Input.GetButton("B"))
{
print("B");
}
else if (Input.GetButton("C"))
{
print("C");
}
else if (Input.GetButton("D"))
{
print("D");
}
}
}

*Clarification: This code works as is, I just want to optimize it, a switch statement if possible.

A switch block takes one variable and checks if the value of that variable is equal to any of the cases defined inside. For a conversion between chained if/elses into an if your conditions should all looke like comparing the same variable to different values, that’s not what you’re doing in your code.

To turn your code you’ll need to get “the current key being pressed” into a variable, so you can switch between the values you’re interested, but I think there’s no way to get that information since you can have multiple keys being pressed. In fact, you need both the jump and another key pressed at the same time.

Another idea would be to define an axis in the Input configuration for w and s, and another axis for a and d (it’s already there by default), so you don’t have to check 4 keys, just get the value of each axis.

This way, something like this:

float xSpeed = 0f;

if (Input.GetKeyDown("A"))
xSpeed = -1f;
else if (Input.GetKeyDown("D"))
xSpeed = 1f;

becomes:

float xSpeed = Input.GetAxis("Horizontal");

Anyway, this looks like premature optimization, are you sure a few if/else lines actually make some difference? Or you want to optimize for maintenance?

Unfortunately you can’t change something like this to a switch statement. The problem is that the valid inputs are not unique, in other words it’s not only one of them at a time, you could have all of them pressed at once. With the if then statements you’re checking down in priority which you want to make active but there’s no way to do that in a switch statement.

It may not look pretty but it’s probably the best you’re going to get. Optimization early isn’t generally a good thing but best practices never hurt and going forwards I’d say just keep the contents of the if then blocks down to a minimum.