I really need someone to explain this part of code float x = Random.Range(0,2) == 0 ? -1 : 1;
I understand that it generates a random value of either 1 and -1, and that this float x = Random.Range(0,2)
give x a value between 0 and 2, but what does this == 0 ? -1 : 1;
do, and how does it function?
-
Don't use the `unityscript` tag since the JavaScript-like language has been obsolete for sometime now. – May 08 '22 at 01:39
-
It means `float x; if (Random.Range(0, 2) == 0) { x = -1; } else { x = 1; }`. – 41686d6564 stands w. Palestine May 08 '22 at 01:43
-
Other dup-targets: [Question mark and colon in statement. What does it mean?](https://stackoverflow.com/q/6957214/8967612), [C# Syntax Question on Question Mark and Colon](https://stackoverflow.com/q/56436554/8967612) – 41686d6564 stands w. Palestine May 08 '22 at 01:46
4 Answers
This is the conditional operator
The code is equivalent with:
float r = Random.Range(0,2);
float x;
if (r == 0)
x = -1;
else
x = 1;
With the conditional operator x
can be initialized while with the equivalent if
code I show x
must be assigned after initialization. This doesn't matter for float
but for other types it may matter.

- 72,283
- 15
- 145
- 224
As you said Random.Range(0,2)
gives a value between 0 and 2. The question mark in this variable assignment is called a ternary operator and works like this: condition ? assign this value if true : assign this value if false
.
So in your case if it equals 0, x will be set to -1, if it does not it will equal 1
You can find out more here, at the official Microsoft docs

- 89
- 5
A question mark and colon in this circumstance is an inline if
statement using the “ternary conditional operator”.
It acts similarly to an if
statement but within a larger statement on a single line. For example this:
if( a > b )
largest = a;
else
largest = b;
Is equivalent to:
largest = ( a > b ? a : b );
If the conditional statement before the ?
is true
, the whole clause will become the value immediately after the question mark. If the conditional statement before the ?
is false
, the whole clause will become the value immediately after the colon (:
).
You can use more than one of them in a line, for example:
bool a = false;
int i = 3;
Console.WriteLine(“a is “ + ( a ? “true” : “not true” ) + “ and i is “ + ( i == 3 ? “three” : “not three” ) + “!”);
Note that the “else” is not optional.
So in effect the code you posted is saying “if the random number == 0, x=-1, else x=1”.

- 2,660
- 21
- 34
It is ternary operator, it is similar to if else condition.
For example if you write var x = random == 0 ? -1 : 1;
then in terms of if else condition it will be
if(random == 0)
{
x = -1;
}
else
{
x = 1;
}

- 119
- 4