Inline if-else statement with multiple choices

So, I was looking at an Inline if-statement that uses Ternary Operators. This is basically my current code, which I want to make more compact.

private void Move(Vector3 direction) {
    if(direction != Vector3.back && direction != Vector3.forward) 
        transform.Rotate(0,(direction == Vector3.right ? 90 : -90),0);
    else 
        transform.Rotate(0,(direction == Vector3.back ? 180 : 0),0);

    transform.Translate(Vector3.forward, Space.Self);
}

I really want something compacted like this:

private void Move(Vector3 direction) {
    transform.Rotate(0,(direction == Vector3.right ? 90 : -90 || direction == Vector3.back ? 180 : 0),0);
    transform.Translate(Vector3.forward, Space.Self);
}

Is there anyway to do this? Just take this example. I want to know how to compile several built-in if statements, so I don’t need to have more lines of code for no reason if I can avoid it.

Thanks for taking the time to read my question.

+3
source share
2 answers

This is not exactly what you requested, but in the interest of simplifying the method, perhaps try the following:

public enum Direction
{
   Left = -90,
   Right = 90,
   Forward =0,
   Back = 180
}

private void Move(Direction direction) 
{
   transform.Rotate(0,(int)direction,0);
   transform.Translate(Vector3.forward, Space.Self);
}
+3
source

, . Vector3 4 , . , .

private void Move(Vector3 direction)
{
    transform.Rotate(0,
        direction == Vector3.right ? 90 :
            (direction == Vector3.left ? -90
                (direction == Vector3.back ? 180 : 0)), 0);
    ...
}

"", .

:

Color color;

if (title == "VIP")
    color = Color.Red;
else
    color = Color.Blue;

:

var color = (title == "VIP" ? Color.Red : Color.Blue);
+1

All Articles