# Is there a more optimized way of writing a ton of else if statements?

Okay, my code…

float forward = Input.GetAxis("Vertical");
float side = Input.GetAxis("Horizontal");

...

if (forward > 0 && side == 0) { //forward
Debug.Log("Forward");
} else if (forward < 0 && side == 0) { //back
Debug.Log("Back");
} else if (forward == 0 && side > 0) { //right strafe
Debug.Log("Right");
} else if (forward == 0 && side < 0) { //left strafe
Debug.Log("Left");
} else if (forward > 0 && side > 0) { //forward right
Debug.Log("Forward right");
} else if (forward > 0 && side < 0) { //forward left
Debug.Log("Forward left");
} else if (forward < 0 && side > 0) { //back right
Debug.Log("Back right");
} else if (forward < 0 && side < 0) { //back left
Debug.Log("Back left");
}

I would like to know if there is a more optimized, or shorter way of writing this. Also, if you can’t tell by the code, this is C#.

Soooort of. It’s like factoring a math problem - ‘factor out’ the “forward” variable and you get something like this. It’s a bit more sectioned off, so you-the-programmer can better see what’s going on; and in some cases if you know one case is going to happen more often than another, you can put that one first and get a teensy-weensy bit of performance improvement.

if ( forward < 0 ) {
if ( side < 0 ) {
else if ( side > 0 ) {
else {
}
} else if ( forward > 0 ) {
...

You could also overoptimize into a switch statement, at the cost of readability. I’ve used this on occasion, when it made more sense to condense to a single value (for accessing an array, for instance):

var value = 4 + (forward<0?-1:(forward>0?1:0)) + (side<0?-3:(side>0?3:0));

switch ( value ) {
case 0: // -forward, -side
case 1: // 0forward, -side
case 2: // +forward, -side
case 3: // -forward, 0side
case 4: // 0forward, 0side
case 5: // +forward, 0side
case 6: // -forward, +side
case 7: // 0forward, +side
case 8: // +forward, +side
}

to begin with, make some freaking booleans

bool leftright = ( side != 0 )

bool foreback = ( forward != 0 )

bool diagonal = ( leftright && foreback )

bool stopped = ( (!leftright) && (!foreback) )

do that before anything else.

Another approach is, simply have a 2D array with your nine values, and the solution then is

direction = handyArray[ side, forward ];

(obviously just normalise side, forward to -1,0,1 first). that’s the cleanest.