I was creating a simple pong game and I watched a video to see how else it could be done but I don’t understand what the person did. The script is simple and only a small part is unclear as to what exactly it does.
sx = Random.Range (0, 2) == 0 ? -1 : 1;
sy = Random.Range (0, 2) == 0 ? -1 : 1;
The part with the 0 ? -1 : 1; is what confuses me. If someone could explain, I would appreciate it. Thank you!
That’s a conditional operator.
It returns one of two values depending on the value of a Boolean expression.
condition ? first_expression : second_expression;
If the condition is true, the first expression is returned. If it’s false the second expression is returned.
For your situation specifically.
- If sx is 0, then return -1 otherwise, return 1;
- if sy is 0 then retrun -1 otherwise, return 1;
It’s a short-hand equivalent to this:
sx = Random.Range(0, 2);
if(sx == 0)
{
return -1;
}
else
{
return 1;
}
Ah the ternary operator. The single most difficult programming-related thing to Google
1 Like
I really don’t like them much. They’re situational and aren’t easy to read at a glance (for me at least).
1 Like