Reputation: 513
So, I was looking at the Inline if-statement, which taks use of the Ternary Operators. Basically this is 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);
}
What I really want is 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 an example. I want to know how to compact multiple inline if-statements, so I don't have to have more lines of code for no reason, if I can avoid it.
Thanks for taking the time to read my question.
Upvotes: 3
Views: 2416
Reputation: 2381
This isn't exactly what you asked for, but in the interest of making the method more compact, perhaps try this:
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);
}
Upvotes: 4
Reputation: 66439
I'd say that first one is compact enough. If the Vector3
enumeration has 4 values, your second example won't work. And making it work may look just as long as the first example.
private void Move(Vector3 direction)
{
transform.Rotate(0,
direction == Vector3.right ? 90 :
(direction == Vector3.left ? -90
(direction == Vector3.back ? 180 : 0)), 0);
...
}
A ternary operation is most "compact" when you have only two values to test.
For example:
Color color;
if (title == "VIP")
color = Color.Red;
else
color = Color.Blue;
Becomes:
var color = (title == "VIP" ? Color.Red : Color.Blue);
Upvotes: 1